简体   繁体   English

KnockoutJS-如何对在选项扩展内创建的可观察数据进行数据绑定

[英]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: 我在“ extend”中扩展了一个名为“ obsRandom”的可观察对象,它看起来像这样:

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. 我已经阅读了有关http://coderenaissance.github.io/knockout.viewmodel/的文章,该文章解释了viewmodel插件,但是我仍然想不出一种将创建的可观察对象进行数据绑定的方法。

How can we do data-bind our html element 我们如何做数据绑定我们的html元素

input type="radio" data-bind="checked: ???" 输入type =“ radio” data-bind =“ checked:???”

to this new extended observable? 这个新的扩展可观察到的?

I have tried data-bind="checked: $root.options.extend.obsRandom" but doesn't work. 我试过了data-bind =“ checked:$ root.options.extend.obsRandom”,但不起作用。

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: 我以前没有使用过ko.viewmodel库,而且我没有看到足够的代码来给您确切的答案,但是使用浏览器的调试器应该不难:

  1. Remove the data-bind property from the <input> element you want to create. 从要创建的<input>元素中删除data-bind属性。
  2. Add a temporary id attribute to the element: <input id="temp-debug"> 向元素添加一个临时id属性: <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 $root将显示您的root视图模型的样子
    • $data will show you what the element's viewmodel looks like $data将向您显示元素的viewmodel的样子
    • $parents is an array that stores each level between $root and $data $parents是一个数组,用于存储$root$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 例如:您可以通过查询以下debugCtx.$root.options.extend.obsRandom检查尝试返回的路径: debugCtx.$root.options.extend.obsRandom

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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