start
Begin an event batch.
canBatch.start([batchStopHandler])
Parameters
- batchStopHandler
{function}
:a callback that gets called after all batched events have been called.
canBatch.start
begins an event batch. Until stop
is called, any
events that would result from calls to [can-event/batch/batch.trigger] to are held back from firing. If you have
lots of changes to make to observables, batching them together can help performance - especially if
those observables are live-bound to the DOM.
In this example, you can see how the first event is not fired (and their handlers
are not called) until canBatch.stop
is called.
var person = new DefineMap({
first: 'Alexis',
last: 'Abril'
});
person.on('first', function() {
console.log("First name changed.");
}).on('last', function() {
console.log("Last name changed.");
});
canBatch.start();
person.first = 'Alex';
console.log('Still in the batch.');
canBatch.stop();
// the log has:
// Still in the batch.
// First name changed.
You can also pass a callback to canBatch.start
which will be called after all the events have
been fired:
canBatch.start(function() {
console.log('The batch is over.');
});
person.first = "Izzy"
console.log('Still in the batch.');
canBatch.stop();
// The console has:
// Still in the batch.
// First name changed.
// The batch is over.
Calling canBatch.start
multiple times
If you call canBatch.start
more than once, canBatch.stop
needs to be called
the same number of times before any batched events will fire. For ways
to circumvent this process, see stop.
Here is an example that demonstrates how events are affected by calling
canBatch.start
multiple times.
var Todo = DefineMap.extend({
completed: "boolean",
name: "string"
updatedAt: "date",
complete: function(){
canBatch.start();
this.completed = true;
this.updatedAt = new Date();
canBatch.end();
}
});
Todo.List = DefineList.extend({
"#": Todo,
completeAll: function(){
this.forEach(function(todo){
todo.complete();
});
}
});
var todos = new Todo.List([
{name: "dishes", completed: false},
{name: "lawn", completed: false}
]);
todos[0].on("completed", function(ev){
console.log("todos[0] "+ev.batchNum);
})
todos[1].on("completed", function(ev){
console.log("todos[1] "+ev.batchNum);
});
todos.completeAll();
// console.logs ->
// todos[0] 1
// todos[1] 1