Calling the method provided in HTML in a Knockout custom binding tool

In my current project, I use both knockout.js and hammer.js. I created a special binding handler for the tap event in hammer.js (this should also work for other events like hold or swipe). My problem is that in this binding handler I want to call the method that I provide in the data binding attribute in HTML. According to the knockout documentation, I found out that I have to call valueAccessor (), but unfortunately it does nothing. I created this script that should give you a clear example of my problem. Thanks 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!");
    }
});
0
1

valueAccessor , . , 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
        };
    }
}

​​

+1

Source: https://habr.com/ru/post/1538046/


All Articles