回调函数
开发工具与关键技术:VS JQ
作者:唐文坚
撰写时间:2020.9.18
callbacks.add(callbacks):
回调列表中添加一个回调或回调的集合。
Callbacks: 一个函数,或者一个函数数组用来添加到回调列表
JQ代码;
// a sample logging function to be added to a callbacks list
var foo = function( value ){
console.log( ‘foo:’ + value );
}
// another function to also be added to the list
var bar = function( value ){
console.log( ‘bar:’ + value );
}
var callbacks = $.Callbacks();
// add the function ‘foo’ to the list
callbacks.add( foo );
// fire the items on the list
callbacks.fire( ‘hello’ );
// outputs: ‘foo: hello’
// add the function ‘bar’ to the list
callbacks.add( bar );
// fire the items on the list again
callbacks.fire( ‘world’ );
// outputs:
// ‘foo: world’
// ‘bar: world’
callbacks.disable():
禁用回调列表中的回调,使用 callbacks.disable() 禁用回调列表:
代码:
// a sample logging function to be added to a callbacks list
var foo = function( value ){
console.log( value );
}
var callbacks = $.Callbacks();
// add the above function to the list
callbacks.add( foo );
// fire the items on the list
callbacks.fire( ‘foo’ ); // outputs: foo
// disable further calls being possible
callbacks.disable();
// attempt to fire with ‘foobar’ as an argument
callbacks.fire( ‘foobar’ ); // foobar isn’t output
callbacks.empty():
从列表中删除所有的回调.
使用 callbacks.empty() 清空回调列表:
代码:
// a sample logging function to be added to a callbacks list
var foo = function( value1, value2 ){
console.log( ‘foo:’ + value1 + ‘,’ + value2 );
}
// another function to also be added to the list
var bar = function( value1, value2 ){
console.log( ‘bar:’ + value1 + ‘,’ + value2 );
}
var callbacks = $.Callbacks();
// add the two functions
callbacks.add( foo );
callbacks.add( bar );
// empty the callbacks list
callbacks.empty();
// check to ensure all callbacks have been removed
console.log( callbacks.has( foo ) ); // false
console.log( callbacks.has( bar ) ); // false
callbacks.fire(arguments):
禁用回调列表中的回调,arguments:这个参数或参数列表传回给回调列表。
使用 callbacks.fire() 用任何已传递的参数调用列表中的回调:
代码
// a sample logging function to be added to a callbacks list
var foo = function( value ){
console.log( ‘foo:’ + value );
}
var callbacks = $.Callbacks();
// add the function ‘foo’ to the list
callbacks.add( foo );
// fire the items on the list
callbacks.fire( ‘hello’ ); // outputs: ‘foo: hello’
callbacks.fire( 'world '); // outputs: ‘foo: world’
// add another function to the list
var bar = function( value ){
console.log( ‘bar:’ + value );
}
// add this function to the list
callbacks.add( bar );
// fire the items on the list again
callbacks.fire( ‘hello again’ );
// outputs:
// ‘foo: hello again’
// ‘bar: hello again’