Calling the method provided in HTML in Knockout custom bindinghandler

心不动则不痛 提交于 2019-12-13 04:42:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!