问题
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!");
}
});
回答1:
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
};
}
}
Updated fiddle
来源:https://stackoverflow.com/questions/13918005/calling-the-method-provided-in-html-in-knockout-custom-bindinghandler