BaseViewModel
Backbone like model extension for knockout viewmodels, including automatic observable and computed function creation for model properties. Based on ideas in bmac's BaseViewModel and jcreamer898's ko.ninja. Uses Backbone's extend function to provide inheritance. BaseViewModel Project Page.
Getting started
If you wish to contribute to BaseViewModel's development, clone the project and install the dependencies with npm install
. That's it!
To build the files for deployment, run grunt build
.
BaseViewModel is available on npm and bower and is a UMD module.
Examples
Create a BaseViewModel sub-class
You can extend the BaseViewModel class by using the extend
method, passing in an object to be copied over to the new sub-class. Additionally, passing in a defaults hash will create default model observables on the sub-class.
var Person = BaseViewModel; var me = ;metype; // 'Human'me; // 'Species: Human'
Passing a model
As well as sub-classing, you can pass an object to the BaseViewModel class or one of it's sub-classes to act as the model for that view model.
var meModel = name: 'Lee' age: 28 address: city: 'London' { return 'Hello, I\'m ' + thisname + ' from ' + thisaddress; }; var me = meModel;mename; // 'Lee'me; // 28meaddress; // 'London'me; // 'Hello, I'm Lee from London'
Getting back the model
To return the original model there is a toModel method to return the original model as an object, or a toJSON method that returns a JSON representation of the original model. Both methods ignore default properties.
var model = foo: 'foo' bar: 'bar';var VM = defaults: foobar: 'foobar' ;var myVM = model;var obj = myVM;var objJSON = myVM; console; // undefinedconsole; // 'foo'console; // { foo: 'foo', bar: 'bar' }console; // '{"foo":"foo","bar":"bar"}'