2011-10-05 14 views
6

我目前使用Function.apply來調用具有動態數量參數的函數,但我無法訪問原始上下文,也沒有任何願望自己設置上下文。我想要的是能夠調用具有可變數量參數的函數,並保留原始上下文。使用原始上下文調用帶有未知數量參數的Javascript函數

或許有些代碼應該告訴你什麼是我想要做的事:

function MulticastDelegate() { 
    var handlers = []; 

    this.event = { 
     subscribe: function(handler) { 
      if (typeof(handler) === 'function') { 
       handlers.push(handler); 
      } 
     }, 
     unsubscribe: function(handler) { 
      if (typeof(handler) === 'function') { 
       handlers.splice(handlers.indexOf(handler),1); 
      } 
     } 
    } 

    this.execute = function() { 
     var args = Array.prototype.slice.call(arguments); 
     for (var handler in handlers) { 
      // call this with the original context of the handler 
      handlers[handler].apply(null, args); 
     } 
    } 
} 

從本質上講,我想的apply行爲 - 的能力來傳遞參數數組 - 無call行爲 - 改變函數執行的上下文。

回答

5

功能的「原始上下文」沒有這樣的東西。你將不得不做這樣的事情:

subscribe: function(handler, context) { 
    if (typeof(handler) === 'function') { 
     handlers.push([handler, context]); 
    } 
}, 

然後,當然,

handlers[handler][0].apply(handlers[handler][1], args); 

或者(這是我會做什麼),它留給調用者,以確保處理器具有正確的背景。例如,而不是delegate.subscribe(this.foo),說

var self = this 
delegate.subscribe(function() { self.foo() }) 

或者,使用Function.prototype.bind

delegate.subscribe(this.foo.bind(this)) 
+0

我想你在這裏描述的是什麼呢Backbone.js的在其事件綁定框架:http://documentcloud.github.com /backbone/docs/backbone.html#section-12 – nrabinowitz

+0

@nrabinowitz哈哈! GMTA :) –

+0

我認爲你是正確的讓調用者照顧它執行的上下文,通過使用'var self'方法或類似的東西。然後我可以爲'this'提供一個更合適的對象。 –

相關問題