Question

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!");
    }
});
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top