0

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

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

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

    return self;
}());

module.OnChange(callbackFunction);

function callbackFunction(event){
    //do staff
}

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

4

2 回答 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 );
  }
}
于 2012-09-16T13:32:40.630 回答
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
}

你到底想做什么?

于 2012-09-16T13:31:51.767 回答