调用回调的事件调用回调

时间:2012-09-16 13:23:32

标签: javascript javascript-events module callback

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

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

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

    return self;
}());

module.OnChange(callbackFunction);

function callbackFunction(event){
    //do staff
}

那么,关于如何访问OnChange'callbackFunction'的任何想法?
或者使用模块模式更好的方法吗?

2 个答案:

答案 0 :(得分:2)

我经常在我的modules / plugins / libraries中使用这个模式:

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 );
  }
}

答案 1 :(得分: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
}

你究竟想做什么?