2012-09-16 39 views
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參數' 任何想法?
或更好的方式來做到這一點的模塊模式?

回答

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

感謝。這裏是一個小演示http://jsbin.com/eqovak/4/edit – Daniel

+0

@Daniel酷:)沒問題......它是相當煩人的'參數'對象不支持正常的數組方法,直到你已經轉換它 - 否則代碼將相當整齊。哦,順便說一句,我已經添加了一個更好的版本,擺脫了數組shift()的需要。 – Pebbl

+0

再次感謝,這是一個非常優雅的解決方案。 http://jsbin.com/eqovak/5/edit – Daniel

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 
} 

究竟是你想做些什麼?