事件调用回调,它调用回调

问题描述 投票:0回答:2

我正在实现模块模式,我想公开一个事件函数。这是代码:

var module = (function(){
    var self = {},
        cb = $(":checkbox");

    cb.on("change",/* self.OnChange */ ); // ???

    return self;
}());

module.OnChange(callbackFunction);

function callbackFunction(event){
    //do staff
}

所以,关于如何访问OnChange'callbackFunction'的任何想法?还是使用模块模式执行此操作的更好方法?

javascript module callback dom-events
2个回答
2
投票
我经常在我的模块/插件/库中使用此模式:

var borrow = function( obj, funcName, funcArg ){ return function(){ /// convert arguments to array var args = Array.prototype.slice.call( arguments ); /// add in our fixed arg 'change' args.unshift( funcArg ); /// execute the function return obj[funcName].apply( obj, args ); } } self.change = borrow( cb, 'on', 'change' );

这意味着您可以在构造函数之外调用:

module.change( callbackFunction );

这基本上具有直接借用jQuery函数的效果,但是将其与您选择的特定元素包装在一起。上面的代码会将您的事件监听器直接传递到该复选框,就像您直接键入以下内容一样:

cb.on( 'change', callbackFunction );

您可以改进上述内容以接受多个固定参数,例如:

var borrow = function( obj, funcName ){ /// convert arguments to array var args1 = Array.prototype.slice.call( arguments ); /// remove the first two args (obj & funcName) /// which means we now have an array of left over arguments /// we'll treat these as 'fixed' and always passed to the /// 'borrowed' function. args1.shift(); args1.shift(); /// return a closure containing our 'borrowed' function return function(){ /// convert arguments to array var args2 = Array.prototype.slice.call( arguments ); /// create a new array combined from the fixed args and the variable ones var args = args1.concat( args2 ); /// execute the function return obj[funcName].apply( obj, args ); } }

进一步的改进

(摆脱转变)就像这样:

var borrow = function( obj, funcName ){ /// convert arguments to array and remove first two arguments var args1 = Array.prototype.slice.call( arguments, 2 ); /// return a closure containing our 'borrowed' function return function(){ /// convert arguments to array var args2 = Array.prototype.slice.call( arguments ); /// create a new array combined from the fixed args and the variable ones var args = args1.concat( args2 ); /// execute the function return obj[funcName].apply( obj, args ); } }

0
投票
我认为您正在造成一些困惑

var module = (function(){ // here this points to the window object var self = this, cb = $(":checkbox"); cb.on("change",/* self.OnChange */ ); // ??? // here you are returning the window object return self; }()); //since the function was instantaneous, here you are calling onChange() on the window object module.OnChange(callbackFunction); function callbackFunction(event){ //do staff }

您到底想做什么?    
© www.soinside.com 2019 - 2024. All rights reserved.