首先是一个简单的回调的例子: /** * 回调函数测试方法 * @param callback * 被回调的方法 */
首先是一个简单的回调的例子:
/** * 回调函数测试方法 * @param callback * 被回调的方法 */ function testCallback(callback) { alert('测试回调函数'); callback(); } /** * 被回调的函数 */ function a() { alert('回调了'); } /** * 开始测试方法 */ function test() { testCallback(a); } test();
以下用jquery的trigger实现:
$(function(){ function testCallback() { alert('开始触发自定义事件'); $(window).trigger('test'); } /** * 被触发的函数 */ $(window).on('test',function(){ alert(''); }) /** * 开始测试方法 */ function test() { testCallback(); } test();})
这样就实现了使用jquery的trigger触发自定义事件实现类似回调的功能。