简体   繁体   English

敲除按钮上的自定义绑定

[英]Knockout custom binding on button

I have some issues creating a custom binding. 创建自定义绑定时遇到一些问题。 From what i understand the update callback of the binding should fire every time the view model changes. 据我了解,每次视图模型更改时,都应触发绑定的更新回调。

I have created a small example. 我创建了一个小例子。

http://jsfiddle.net/alexmaie/pbEmS/ http://jsfiddle.net/alexmaie/pbEmS/

  ko.bindingHandlers.testBinding = {

     update: function(element, valueAccessor, allBindingsAccessor, viewModel,       bindingContext) {
//just for testing purposes
     alert("update");
  }
};

$(document).ready(function() {
function AppViewModel() {
    var self = this;
    self.firstName = ko.observable("Bert");

}
ko.applyBindings(new AppViewModel());
});​

There i attach a binding to a button. 在那里我将绑定绑定到按钮。 The update of the binding is executed one time, and then never again, even if i change the data of the observable. 绑定的更新执行一次,然后再也不会执行,即使我更改了可观察的数据也是如此。

I want to use this approach to implement an canExecute binding. 我想使用这种方法来实现canExecute绑定。

Bindings are implemented inside of a computed observable , so they track dependencies based on the observables/computeds that are actually accessed. 绑定是在computed observable内部实现的,因此它们根据实际访问的observable / computes跟踪依赖关系。

So, this means that in your update function, you would want to access the value of the observable that was passed to it like: 因此,这意味着在update函数中,您将希望像以下那样访问传递给它的可观察对象的值:

   ko.bindingHandlers.testBinding = {   
      update: function(element, valueAccessor) {
         //dependency is created here
         var value = ko.utils.unwrapObservable(valueAccessor());
         alert("update " + value);
      }
   }

Updated fiddle: http://jsfiddle.net/rniemeyer/pbEmS/2/ 更新小提琴: http : //jsfiddle.net/rniemeyer/pbEmS/2/

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

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