Removing the element of observablearray in Knockoutjs

advertisements

I am trying to learn Knockoutjs and I am having some issues with adding and removing objects to an observablearray.

I have the following viewmodel in which I fetch some data from a webservice and populate some html. This works fine. But what does not work is removing items from the observablearray since it seems the click-event does not call removeEmployee.

function EmployeeViewModel(){
    var self=this;

    self.employees=ko.observableArray();

    self.removeEmployee = function(item) {
        self.employees.remove(item);
    };
}

function success(data) {
    EmployeeViewModel.employees=ko.mapping.fromJS(data);
    ko.applyBindings(EmployeeViewModel);
};

ApiCall({
    data: {
      [get data]
    },
    onSuccess: function(data){success(data.result)}
});

and the following html:

<div data-bind="foreach: employees">
    <h2>Hello, <span data-bind="text: full_name"> </span>!</h2>
    <button data-bind="click: $parent.removeEmployee">Remove</button>
 </div>

I have tried setting up a jsfiddle here: http://jsfiddle.net/8yX5M/ in which removing items does work. The difference is, that in the jsfiddle the items are not fetched from an external source and that I use removeEmployee rather than $parent.removeEmployee.

Any ideas why the non-jsfiddle version is not working ?

thanks Thomas


Because your success function isn't setting the value of the observableArray, it is resetting the object's definition -

function success(data) {
    EmployeeViewModel.employees(ko.mapping.fromJS(data));
    ko.applyBindings(EmployeeViewModel);
};

Use the setter function on EmployeeViewModel.employees by using the () and passing in a value.