start

  • function
 

Begin an event batch.

can.batch.start([batchStopHandler])

Parameters

  1. batchStopHandler {function()}Optional

    a callback that gets called after all batched events have been called

can.batch.start causes can.Map to begin an event batch. Until can.batch.stop is called, any events that would result from calls to attr are held back from firing. If you have lots of changes to make to can.Maps, batching them together can help performance &emdash; especially if those can.Maps are live-bound to the DOM.

In this example, you can see how the first and change events are not fired (and their handlers are not called) until can.batch.stop is called.

var person = new can.Map({
    first: 'Alexis',
    last: 'Abril'
});

person.bind('first', function() {
    console.log("First name changed."");
}).bind('change', function() {
    console.log("Something changed.");
});

can.batch.start();
person.attr('first', 'Alex');
console.log('Still in the batch.');
can.batch.stop();

// the log has:
// Still in the batch.
// First name changed.
// Something changed.

You can also pass a callback to can.batch.start which will be called after all the events have been fired:

can.batch.start(function() {
    console.log('The batch is over.');
});
person.attr('first', 'Izzy');
console.log('Still in the batch.');
can.batch.stop();

// The console has:
// Still in the batch.
// First name changed.
// Something changed.
// The batch is over.

Calling can.batch.start multiple times

If you call can.batch.start more than once, can.batch.stop needs to be called the same number of times before any batched events will fire. For ways to circumvent this process, see can.batch.stop.

Here is an example that demonstrates how events are affected by calling can.batch.start multiple times.

var addPeople = function(observable) {
    can.batch.start();
    observable.attr('a', 'Alice');
    observable.attr('b', 'Bob');
    observable.attr('e', 'Eve');
    can.batch.stop();
};

// In a completely different place:
var list = new can.Map();
list.bind('change', function() {
    console.log('The list changed.');
});

can.batch.start();
addPeople(list);
console.log('Still in the batch.');

// Here, the console has:
// Still in the batch.

can.batch.stop();

// Here, the console has:
// Still in the batch.
// The list changed.
// The list changed.
// The list changed.