Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
86 lines (53 sloc) 3.23 KB

Build Status Dependency Status


Yes, YA Backbone.ViewModel here! Because we are can! :)

Actually I need solutions to link two different Views on base of one Model and ViewModel is matter. For mode details and examples see demo project and live result.


Backbone.ViewModel may used between Model and View in Backbone or BB.Marionette or other BB-compatibility projects.

Its not drop-in replacement for Model, but it handle correctly some methods and properties form Model and should play well with others (you may write request with testcase if important Madel functionality looks omitted).

As ViewModel its support some additional features as computed values, controlled autosync with Model and defaults values.



npm install backbone.viewmodel


Get copy of /browser_lib/backbone.viewmodel.js or use CommonJS-style with clinch.


All examples written with CoffeeScript, you may use plain JS instead (but why?).

How its works:

class RectangleViewModel extends Backbone.ViewModel
  autoupdate  : on
  mapping : 
    color   : 'color'
    width   : 'size'
    height  : 'getHeight'
  getHeight : ->
    @model.get('size') * ( 1 + Math.random() ) | 0

rectangle = new RectangleViewModel color : 'blue', size : 20
console.log rectangle.toJSON() # -> Object {color: "blue", width: 20, height: 22} 

rectangle.model.set 'size', 50 # its bad example of `model` interaction, but ok here
console.log rectangle.toJSON() # -> Object {color: "blue", width: 50, height: 74} 


Backbone.ViewModel have few methods and some numbers of class properties.


# model prop may be used to create specific Model from raw data
model       : BaseBB.Model  # default Backbone.Model
#track model changes and auto-update self state
autoupdate  : on            # default off
all keys in mapping will be 'mapped' self VM functions OR
model attributes, with priority: function, than attributes
mapping :                   # default {}
  color   : 'color'
  height  : 'getHeight'


constructor(dataIn, constructorAttrs, options)

  • dataIn - BB.Model or raw data object
  • constructorAttrs - default VM properties may be placed here
  • options - some options, like autoupdate


Just proceed process to update VM from current model state. May be called if autoupdate property not used for any reason.

BB.Model methods

Backbone.ViewModel as BB.Model will support some helpfully methods like toJSON() or get(), dozen unsuitably methods like set() unset() or clear() and (at now) will available to call erroneously methods like fetch() or sync() - just do not use them.

If you need to have synced model - create it first and use thyself methods in ViewModel update or autoupdate combinations.