replace

  • function
can.List.prototype.replace  

Replace all the elements of a List.

list.replace(collection)

Parameters

  1. collection {Array | can.List | can.Deferred}

    the collection of new elements to use If a can.Deferred is passed, it must resolve to an Array or can.List. The elements of the list are not actually removed until the Deferred resolves.

replace replaces all the elements of this List with new ones.

replace is especially useful when can.Lists are live-bound into can.Controls, and you intend to populate them with the results of a can.Model call:

can.Control({
    init: function() {
        this.list = new Todo.List();
        // live-bind the list into the DOM
        this.element.html(can.view('list.mustache', this.list));
        // when this AJAX call returns, the live-bound DOM will be updated
        this.list.replace(Todo.findAll());
    }
});

Learn more about making Lists of models.

Events

A major difference between replace and attr(newElements, true) is that replace always emits an add event and a remove event, whereas attr will cause set events along with an add or remove event if needed. Corresponding change and length events will be fired as well.

The differences in the events fired by attr and replace are demonstrated concretely by this example:

var attrList = new can.List(['Alexis', 'Bill']);
attrList.bind('change', function(ev, index, how, newVals, oldVals) {
    console.log(index + ', ' + how + ', ' + newVals + ', ' + oldVals);
});

var replaceList = new can.List(['Alexis', 'Bill']);
replaceList.bind('change', function(ev, index, how, newVals, oldVals) {
    console.log(index + ', ' + how + ', ' + newVals + ', ' + oldVals);
});

attrList.attr(['Adam', 'Ben'], true);         // 0, set, Adam, Alexis
                                              // 1, set, Ben, Bill
replaceList.replace(['Adam', 'Ben']);         // 0, remove, undefined, ['Alexis', 'Bill']
                                              // 0, add, ['Adam', 'Ben'], ['Alexis', 'Bill']

attrList.attr(['Amber'], true);               // 0, set, Amber, Adam
                                              // 1, remove, undefined, Ben
replaceList.replace(['Amber']);               // 0, remove, undefined, ['Adam', 'Ben']
                                              // 0, add, Amber, ['Adam', 'Ben']

attrList.attr(['Alice', 'Bob', 'Eve'], true); // 0, set, Alice, Amber
                                              // 1, add, ['Bob', 'Eve'], undefined
replaceList.replace(['Alice', 'Bob', 'Eve']); // 0, remove, undefined, Amber
                                              // 0, add, ['Alice', 'Bob', 'Eve'], Amber