• function

startBatch can.Observe.startBatch

 

Begin an event batch.

can.Observe.startBatch([batchStopHandler])

Parameters

  1. batchStopHandler {function()}Optional

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

startBatch causes can.Observe to begin an event batch. Until can.Observe.stopBatch 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.Observes, batching them together can help performance &emdash; especially if those can.Observes 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 stopBatch is called.

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

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

can.Observe.startBatch();
person.attr('first', 'Alex');
console.log('Still in the batch.');
can.Observe.stopBatch();

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

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

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

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

Calling startBatch multiple times

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

Here is an example that demonstrates how events are affected by calling startBatch multiple times.

var addPeople = function(observable) {
    can.Observe.startBatch();
    observable.attr('a', 'Alice');
    observable.attr('b', 'Bob');
    observable.attr('e', 'Eve');
    can.Observe.stopBatch();
};

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

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

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

can.Observe.stopBatch();

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