knockout.js - Get ViewModel from DOM element

Javascriptknockout.js

Javascript Problem Overview


is is possible to get the binded ViewModel JavaScript object from a given DOM element?

ko.applyBindings( gLoginViewModel, document.getElementById("login-form") );
ko.applyBindings( gLoginViewModel, document.getElementById("register-form") );

and somewhere else - in rather unrelated code - something like this:

var viewModel = ko.getViewModel( formElement );
viewModel.someObservable( someData ); // observable available in all ViewModels

it would even be better if I could do something like:

var viewModel = ko.getViewModel( someChildElement );

Javascript Solutions


Solution 1 - Javascript

Knockout has two utility methods that might help here.

  • ko.dataFor will return the ViewModel that the element is bound to.

  • ko.contextFor returns the "binding context" of the current element. The object you get back from this method will return something like:

      { 
          $data: ...,
          $parents,
          $root
      }
    

So if I understand your question, you can probably use ko.dataFor here. Here's a simple example using dataFor.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDirk BoerView Question on Stackoverflow
Solution 1 - JavascriptAndrew WhitakerView Answer on Stackoverflow