xdrnc
xdrnc

Reputation: 330

KnockoutJS - How to data-bind an observable that is created inside options extend

I am extending an observable called "obsRandom" inside "extend" which looks like this:

var options = {
       extend: {
          "{root}": function (self) {
             self.obsRandom = ko.observable(true)
........        

I have read about this article http://coderenaissance.github.io/knockout.viewmodel/ that explains the viewmodel plugin, but I still cannot think of a way to data-bind the created observable.

How can we do data-bind our html element

input type="radio" data-bind="checked: ???"

to this new extended observable?

I have tried data-bind="checked: $root.options.extend.obsRandom" but doesn't work.

Upvotes: 0

Views: 86

Answers (1)

user3297291
user3297291

Reputation: 23397

I haven't used the ko.viewmodel library before, and I'm not seeing enough code to give you an exact answer, but it shouldn't be hard to figure out using your browser's debugger:

  1. Remove the data-bind property from the <input> element you want to create.
  2. Add a temporary id attribute to the element: <input id="temp-debug">
  3. Open your console and type:

    var debugCtx = ko.contextFor(document.getElementById("temp-debug"));
    
  4. Explore the element's binding context. The most important parts:
    • $root will show you what your root viewmodel looks like
    • $data will show you what the element's viewmodel looks like
    • $parents is an array that stores each level between $root and $data

Using the console you can try out different queries and find out the right data-bind. For example: you can check what the path you tried returns by querying: debugCtx.$root.options.extend.obsRandom

Upvotes: 1

Related Questions