简体   繁体   English

淘汰赛Js定制绑定处理程序更新依赖项

[英]Knockout Js custom binding handler update dependency

This post: Knockout: valueAccessor vs viewModel on custom binding handlers? 帖子: 淘汰赛:自定义绑定处理程序上的valueAccessor vs viewModel? makes the following statement about how the viewModel observables are bound within a custom binding handler: "Any observable that has its value accessed will create a dependency." 对自定义绑定处理程序中如何绑定viewModel可观察对象做出以下声明: “任何访问了其值的可观察对象都会创建一个依赖项。”

How do I access a value from the observable X on the viewModel inside a custom binding handler without creating a dependency that makes the custom binding handler to update if X is later changed? 如何在自定义绑定处理程序中从viewModel的可观察X值访问值, 而又不创建一个依赖关系,如果X以后被更改,该依赖关系会使自定义绑定处理程序进行更新?

I made a Fiddle that showcases this. 我做了一个小提琴来展示这一点。 The line viewModel.xxx(); 该行viewModel.xxx(); creates a dependency to the "xxx" observable. 创建可观察到的“ xxx”的依存关系。

http://jsfiddle.net/hhw4a/5/ http://jsfiddle.net/hhw4a/5/

Short answer: you can't. 简短的答案:您不能。

Best workaround you have available, afaik: create a plain vanilla JavaScript property, and reference that . 您可以使用的最佳解决方法afaik:创建一个普通的JavaScript属性,并引用属性。 Something like this: 像这样:

function Vm(){
    this.aOb = ko.observable('a value');
    this.a = this.aOb();
}

Now you may reference a in your custom bindings, and changes to aOb will not cause your binding to re-fire. 现在,您可以在自定义绑定中引用a ,并且对aOb的更改不会导致您的绑定重新触发。

And if you want to always keep a in sync with aOb, you can use subscribe: 如果您希望始终与aOb保持同步,则可以使用subscription:

function Vm(){
    this.aOb = ko.observable('a value');
    this.a = this.aOb();

    this.aOb.subscribe(function(newVal){
       this.a = newVal;
    }.bind(this));
}

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

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