简体   繁体   中英

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.

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

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