user1620696
user1620696

Reputation: 11375

How does Knockout JS knows the right parameter to pass?

I have a big doubt about the following: suppose we have the following viewmodel and view respectively

function TableViewModel() {
    var self = this;

    self.someObservableCollection = ko.observableArray();

    self.doWorkWithObjectInCollection(collectionObject) {
        /* Code to process the collectionObject */
    }
}

ko.applyBindings(new TableViewModel());

And the view is like that (supposing we also ran a function to get initial data for the collection):

<table>
    <thead> <!-- Table head here --> </thead>
    <tbody data-bind="foreach: someObservableCollection">
        <tr>
            <td data-bind="text: property1"></td>
            <td data-bind="text: property2"></td>
            <!-- ... -->
            <td><a data-bind="click: $parent.doWorkWithObjectInCollection">Do Work</a></td>
        </tr>
    </tbody>
</table>

Now, it is very interesting that when one clicks on the Do Work link, the function doWorkWithObjectInCollection is called and the parameter passed is the object used in the current row.

How does Knockout knows that the parameter we want to pass is the current object in the foreach loop? And in other cases, how can I know what knockout will pass as a parameter to a function called on some event, like click?

Upvotes: 0

Views: 68

Answers (2)

azurelogic
azurelogic

Reputation: 786

Certain knockout bindings change the binding context. 2 examples of this are foreach and with. Any bindings on elements within an element with a foreach binding are repeated "for each" element in the observable array being bound. Inside of this context, all bindings are relative to an element in the observable array.

Now, when a click binding is used, it always passes the current model for the binding context to the function associated with the click. With normal bindings, this is just the main viewmodel. However, inside of a foreach binding, since the binding context has changed to the current element in the observable array, the current model is that current element. That is why it is the thing that gets passed in.

I hope that makes more sense.

Upvotes: 0

UweB
UweB

Reputation: 4110

Knockout doesn't know you want to pass the object in the collection, it tells you in the documentation that it will do exactly this. You cannot directly influence this behaviour.

See "Note 1" at http://knockoutjs.com/documentation/click-binding.html

Upvotes: 3

Related Questions