0
votes

I have problems understanding why the following code does not work in Knockout.

Example

In javascript, myFunction .bind(...) should return a function containing a call to the FUNCTION1 with the supplied parameters. Am I right?

Theoretically, the following code should work, the passed parameter 'hey' should be received by the this.path.to.method function.

However, it does not, I am getting something like the ViewModel instance instead, followed by the event object.

Why?

I am wondering what it exactly does, to understand if I can use .bind or will I always be forced to wrap it inside a function(){ /* any call here ... */ } within the knockout binding 'click'.

JSFiddle link: http://jsfiddle.net/darknessm0404/X2yd7/

<a data-bind="click: path.to.method.bind('hey', $data)">
    Why p1 and p2 do not receive the good parameters with arguments like ['hey', $data] when click happens?
</a>

function VM(){
    // In my model, I am namespacing things this way:
    this.path = {
        to: {
            method: function(p1, p2) {
                console.log(((p1 === 'hey')?'First parameter is as expected':'First parameter is NOT as expected'));
                debugger;
            }
        }
    }
}
ko.applyBindings(new VM());

JSFiddle link: http://jsfiddle.net/darknessm0404/X2yd7/

Yes it works...

...with data-bind="click: function(){ path.to.method('hey', $data); }"

However, it's less readable than the other one.

What do I not understand with the .bind call?

Thank you for your help.

1

1 Answers

0
votes

The correct syntax is

<a data-bind="click: path.to.method.bind($data, 'hey')">

Demo

See knockout doc's example.

Actually, the first parameter to bind will be passed as the this value in your function.
So the first param in your function is the second param in bind.

Check js doc:

Syntax

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Parameters

thisArg The value to be passed as the this parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the new operator.