Reputation: 85565
I'm trying to understand the jQuery.Callbacks() method with the stopOnFalse flag:
function fn1(value) {
console.log(value);
return false;
}
function fn2(value) {
fn1("fn2 says: " + value);
return false;
}
var callbacks = $.Callbacks("stopOnFalse");
callbacks.add(fn1);
callbacks.fire("foo");
callbacks.add(fn2);
callbacks.fire("bar");
callbacks.remove(fn2);
callbacks.fire("foobar");
In my opinion this should output this:
/*
output:
foo
fn2 says: bar
foobar
*/
But actually this outputs this as of the jQuery docs:
/*
output:
foo
bar
foobar
*/
Please explain it a bit.
Upvotes: 1
Views: 301
Reputation: 1376
To add to the clarification of the above mentioned statement if we do something like this
function fn1( value ) {
console.log( value );
return false;
}
function fn2( value ) {
fn1( "fn2 says: " + value );console.log("called fn2")
return false;
}
var callbacks = $.Callbacks( "stopOnFalse" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
the output will be
foo
bar
foobar
as the fn2 never gets called now if we change the code to this
function fn1( value ) {
console.log( value );
return true;
}
function fn2( value ) {
fn1( "fn2 says: " + value );
return false;
}
var callbacks = $.Callbacks( "stopOnFalse" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
the output will be as you had expected earlier
foo
bar
fn2 says: bar
foobar
because the second time fn2 gets called.hope that helps.
Upvotes: 1
Reputation: 388316
Because since fn is added first, it is called first and since it returns false rest of the callbacks are ignored - thus fn2 is never called
function fn1(value) {
console.log('fn', value);
return false;
}
function fn2(value) {
fn1("fn2", value);
return false;
}
var callbacks = $.Callbacks("stopOnFalse");
callbacks.add(fn1);
callbacks.fire("foo");
callbacks.add(fn2);
callbacks.fire("bar");
callbacks.remove(fn2);
callbacks.fire("foobar");
Demo: Fiddle
Upvotes: 2