Wildhoney
Wildhoney

Reputation: 4969

With KnockoutJS, how do you specify the ViewModel to bind to?

It's a pretty simple question, so I'm really hoping for a simple solution. I don't want to use any of the external templating libraries, because whilst I am familiar with EmberJS, Ember would be overkill for the application I'm currently working on.

I've set-up a quick JSFiddle: http://jsfiddle.net/zeEFP/3/

Upvotes: 0

Views: 204

Answers (2)

WickyNilliams
WickyNilliams

Reputation: 5308

In your initial fiddle you are applying the view model to the entire dom (or more specifically window.document.body) because you are not supplying a context element. Therefore you do not need the with binding (the with binding creates a new binding context whereas you're already in the correct binding context)

See: http://jsfiddle.net/zeEFP/10/

If you wish for multiple view models then you can supply a context to the applyBindings method:

ko.applyBindings(new FirstViewModel(), document.getElementById("someId));

See the updated fiddle here: http://jsfiddle.net/zeEFP/8/

If you do not like having additional markup to supply as a context for the applyBindings you can instead use an over-arching view model and then use the with binding to create new contexts for parts of the page

See: http://jsfiddle.net/zeEFP/11/

Hope that helps clear things up for you

Upvotes: 1

daedalus28
daedalus28

Reputation: 1637

ko.applyBindings() takes the viewmodel as a parameter. I've updated your fiddle:

http://jsfiddle.net/zeEFP/4/

It was failing before because you were telling knockout to look for properties within the ViewModel property of the ViewModel object

Upvotes: 1

Related Questions