简体   繁体   中英

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM