我正在尝试使用stopOnFalse标志来理解jQuery.Callbacks()方法:
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");
在我看来,这应该输出:
/*
output:
foo
fn2 says: bar
foobar
*/
但实际上这会从jQuery文档中输出:
/*
output:
foo
bar
foobar
*/
请解释一下。
答案 0 :(得分:2)
因为首先添加fn,所以首先调用它,因为它返回false,所以忽略了其余的回调 - 因此永远不会调用fn2
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");
演示:Fiddle
答案 1 :(得分:1)
如果我们做这样的事情,请添加上述陈述的说明
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" );
输出将是
foo
bar
foobar
因为如果我们将代码更改为此
,fn2现在永远不会被调用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" );
输出将如您之前所预期的那样
foo
bar
fn2 says: bar
foobar
因为第二次fn2被调用.hope有帮助。