kmalakoff/knockback — Issue #14: Monkey patch BB classes to provide simpler interface
Author: yuchi
Created: 2011-11-10 22:43:51+00:00
State: open
Labels: idea, needs review

```coffeescript
ContactViewModel = (model) ->
kb.observables(model, {
name: {key:'name'}
email: {key:'email', write: true, default: 'your.name@yourplace.com'}
date: {key:'date', write: true, localizer: (value) => return new LongDateLocalizer(value)}
}, this)
return this

# later ...

view_model = new ContactViewModel(collection.get('some_id'))
ko.applyBindings(view_model)

```

Actually does a) build a ViewModel, b) engage the created ViewModel with KO.

What about:

```coffeescript
# In Knockback
# -------------------

Backbone.Model::buildView = (viewModel = @viewModel) ->
@view = new viewModel this
ko.applyBindings @view
@

# later, in the application
# --------------------

MyModel = Backbone.Model.extend
# many thinks here
viewModel: (model) ->
kb.observables(model, {
name: {key:'name'}
email: {key:'email', write: true, default: 'your.name@yourplace.com'}
date: {key:'date', write: true, localizer: (value) => return new LongDateLocalizer(value)}
}, @)
@

initialize: (options = {}) ->
# ...and for very lazy people
@buildView()

```

With such an architecture everything is inside the BB.Model definition, but you can always do `MyModel::ViewModel = MyViewModel` if you want to declare the ViewModel in a different place.