Search code examples
knockout.jsko.observablearray

Why can't I remove observables added after binding?


http://jsfiddle.net/scottbeeson/SRUKN/16/

Clicking on items in the left list adds them to the right list. Clicking on items in the right list should remove them. It removes the first one, which is already there, but it will not remove added items. Do I need to reapply the binding or something?

ko.applyBindings(viewModel);

$('.result').on('click',function() {
    var item = ko.dataFor(this);
    viewModel.visibleItem.push(item);
});

$('.visibleItem').on('click',function() {
    var item = ko.dataFor(this);
    viewModel.visibleItem.remove(item);
});

Solution

  • Your click handler only gets attached to the elements which are already in the DOM. If you want make it work for the dynamically added elements you need attach your handler on the a highler level which is already in the DOM and does not change (for example the document or in your case .top):

    $(document).on('click', '.visibleItem', function() {
        var item = ko.dataFor(this);
        console.log(item)
        viewModel.visibleItem.remove(item);
    });
    

    Demo JSFiddle.

    But the Kncokout way is to let Knockout handle your events:

    So add the handler on your viewmodel:

    viewModel.removeVisible = function(item) {
        viewModel.visibleItem.remove(item);
    }
    

    And bind it in your view:

    <div class="visibleItem" data-bind="click: $parent.removeVisible">
    </div>
    

    Demo JSFiddle.