简体   繁体   English

可观察与数据绑定之间的KnockoutJS关系

[英]KnockoutJS relation between observable and data-bind

I Have viewModel 我有viewModel

var viewModel = {
    amount: ko.observable(1),
    rate: ko.observable(2),
    rate222: ko.observable(2)
};


<input data-bind="value: amount" />
<input data-bind="value: rate" />

How do I know that rate222 not bind on this document? 我怎么知道rate222在此文档上不绑定?

  • For need it for multi-page validation, for declared on exist document! 需要用于多页验证,用于在现有文档上声明!

best regards 最好的祝福


UPD: UPD:

This does not resolve this problem here jsfiddle.net/x26sS/14 Bind value "rate222" not in the DOM, but the knockout does not think so: "show,rate12312". 此处无法解决此问题jsfiddle.net/x26sS/14不在DOM中绑定值“ rate222”,但敲除并不这样认为:“ show,rate12312”。

There is not a great way in Knockout to know specifically that an element is bound out-of-the-box. 在Knockout中,没有一种很好的方法可以明确地知道一个元素是开箱即用的。

It would be pretty easy to write a custom binding that adds a bound flag to an observable or computed that you could then use when looking for "unbound" properties. 编写自定义绑定将bound标志添加到可观察的或计算的,然后在查找“未绑定”属性时可以使用的计算将非常容易。

The binding could just look like: 绑定可能看起来像:

ko.bindingHandlers.track = {
    init: function(element, valueAccessor) {
       var observable = valueAccessor();
       if (ko.isObservable(observable)) {
           observable.bound = true;  
       }

       //clear the flag if this element is removed
       ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            var observable = valueAccessor();
            if (ko.isObservable(observable)) {
                observable.bound = false;     
            }     
       });           
    }
};

You could even wrap the value binding to add this functionality into it. 您甚至可以包装值绑定以在其中添加此功能。

Here is a sample that uses this binding on the elements and then provides a function to loop through view model (only top-level in sample) and find any unbound properties. 这是一个在元素上使用此绑定的示例,然后提供了一个遍历视图模型的功能(仅在示例中为顶级)并查找任何未绑定的属性。

http://jsfiddle.net/rniemeyer/x26sS/ http://jsfiddle.net/rniemeyer/x26sS/

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

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