Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.Callbacks().disable() vs $.Callbacks().lock()

Tags:

jquery

The jQuery documentation for both basically states the same thing so I was wondering if there's any major difference, if any, between the two. Thanks!

like image 651
Kpower Avatar asked Sep 03 '12 18:09

Kpower


1 Answers

The documentation on this is actually really bad, so here's what I found by studying the source code:

lock only prevents future fire calls, but does not prevent functions to be added.


Here's a quick rundown of the methods:

  • empty - Removes any callbacks registered thus far.
  • lock - Prevents further calls to fire, but allows more callbacks to be added.
  • disable - Prevents further calls to both fire & add.

To understand all this, let's start with an explanation of the memory flag:

If the callback object is constructed with the memory flag, it'll keep track of the last fire call, and any callback added later will immediately be called. Here's an example:

var callbacks = $.Callbacks('memory');

callbacks.add(function(){
    console.log('first');
});

callbacks.fire();

callbacks.add(function(){
    console.log('second');
});

This'll also log second, even though it was added after the fire call.


If you disable it though, it'll completely wipe the memory. Here's another example:

var callbacks = $.Callbacks('memory');

callbacks.add(function(){
    console.log('first');
});

callbacks.fire();
callbacks.disable();

callbacks.add(function(){
    console.log('second');
});

callbacks.fire();

This'll only log first, since callbacks has been disabled before the second function was added.


However, if you use lock it instead, functions added later will be called. Here's another example:

var callbacks = $.Callbacks('memory');

callbacks.add(function(){
    console.log('first');
});

callbacks.fire();
callbacks.lock();

callbacks.add(function(){
    console.log('second');
});

callbacks.fire();

This'll also log second, but only once; since the object was locked, any further calls to fire will be ignored.

like image 191
Joseph Silber Avatar answered Sep 29 '22 17:09

Joseph Silber