Andrea Casaccia
Andrea Casaccia

Reputation: 4971

Why is a foreach data binding not creating a $parent context?

In the following code, why is the remove handler accessible without $parent?

If I use data-bind="click: $parent.remove" I get an error saying that property remove of undefined doesn't exists, but being inside a foreach loop, shouldn't I get a $parent context?

Template:

<ul data-bind="foreach:list">
    <li><!-- ko text: $data --><!-- /ko --> <button data-bind="click: remove">x</button></li>
</ul>

ViewModel:

function ViewModel() {

    var self = this;

    this.list = ko.observableArray(['asd', 'lol', 'rofl']);

    this.remove = function(index){
        console.log('Clicked ' + index);
        self.list.splice(index, 1);
    };

};

ko.applyBindings(ViewModel);

https://jsfiddle.net/3d7nfbr3/3/

Upvotes: 0

Views: 71

Answers (1)

nemesv
nemesv

Reputation: 139758

You are missing the new, when creating your viewmodel.

Your code should look like this:

ko.applyBindings(new ViewModel());

Without the new the this refers to the global window object so your remove function is declared globally, that is why the $parent is not working.

Demo JsFiddle.

Upvotes: 3

Related Questions