在Knockout自定义绑定处理程序中调用HTML中提供的方法 [英] Calling the method provided in HTML in Knockout custom bindinghandler
问题描述
在我当前的项目中,我同时使用了基因敲除(koutout.js)和锤子(hammer.js).我为Hammer.js中的'tap'事件创建了一个自定义绑定处理程序(这也适用于其他事件,例如hold或swipe).我的问题是,在此绑定处理程序中,我想调用在HTML的data-bind属性中提供的方法.根据淘汰赛文档,我发现我应该调用valueAccessor(),但是不幸的是,这没有任何作用.我创建了此小提琴,它应该为您提供有关我的问题的清晰示例.谢谢您的帮助.
I'm using both knockout.js and hammer.js in my current project. I created a custom binding handler for the 'tap' event in hammer.js (this should also work for other events such as hold or swipe). My problem is that in this binding handler, I want to call a method that I provide in the data-bind attribute in HTML. According to the knockout documentation, I found out that I should call valueAccessor(), but unfortunately, this doesn't do anything. I've created this Fiddle, which should give you a clear example of my problem. Thank you for helping me.
HTML:
<button data-bind="tap: myFunction">Click Me</button>
JS:
ko.bindingHandlers.tap = {
'init': function(element, valueAccessor) {
var tap = new Hammer(element);
tap.ontap = function(ev){
//call the method provided in HTML, in this case doSomething();
// I've tried calling valueAccessor(); but this doesn't seem to work
};
}
}
ko.applyBindings({
myFunction: function() {
document.write("BAM!");
}
});
推荐答案
调用valueAccessor
仅使您可以访问在绑定中设置的对象.由于它是一个函数,并且您要调用它,因此必须调用调用valueAccessor
的结果.
Invoking valueAccessor
just gives you access to the object that was set in the binding. Since it is a function and you want to invoke it, you have to invoke the result of calling valueAccessor
.
ko.bindingHandlers.tap = {
'init': function(element, valueAccessor) {
var tap = new Hammer(element);
var value = valueAccessor(); // get the value (the function)
tap.ontap = function(ev){
//call the method provided in HTML, in this case doSomething();
value(); // call the function
};
}
}
这篇关于在Knockout自定义绑定处理程序中调用HTML中提供的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!