2010-06-09 50 views
1

我有兩個由主類編排的類,我想知道如何在這些類之間觸發事件時訪問正確的'this'對象。下面是我有:jQuery使用事件和觸發器訪問'this'對象

// My main class that orchestrates the two worker classes 
function MainClass() 
{ 
    this.workerOne = new ChildWorkerOne(); 
    this.workerOne.bindBehaviors.apply(this.workerOne); 

    this.workerTwo = new ChildWorkerTwo(); 
    this.workerTwo.bindBehaviors.apply(this.workerTwo); 

    // a custom event I'm creating and will be triggered by 
    // a separate event that occurs in workerTwo 
    $(document).bind("customEvent", this.onCustomAction); 
} 

MainClass.prototype.onCustomAction = function(event, data) 
{ 
    // I want to call a method that belongs to 'workerOne'. 
    this.workerOne.makeItHappen(); 

    // However, the 'this' object refers to the 'Document' and 
    // not the 'MainClass' object. 
    // How would I invoke 'makeItHappen' here? 
}; 

ChildWorkerOne.prototype.makeItHappen = function() 
{ 
    // Do a bunch of work here 
}; 

ChildWorkerTwo.prototype.bindBehaviors = function() 
{ 
    $(div).click(function(e){ 
     $.post(url, params, function(data) 
     { 
      // do a bunch of work with this class and then 
      // trigger event to update data with ChildWorkerOne 
      $(document).trigger("customEvent", [data]); 
     } 
    }); 
}; 

我不想合併ChildWorkerOne和ChildWorkerTwo因爲它們不屬於一個整體且MainClass概念應該協調的ChildWorkerOne和ChildWorkerTwo兩個獨立的實體。但是,我確實想調用另一箇中的行爲。

要做到這一點,最好的方法是什麼?

回答

4

你需要堅持的this值,你可以在許多方面做到這一點,jQuery的1.4+爲您提供的$.proxy方法,例如:

//... 
$(document).bind("customEvent", $.proxy(this.onCustomAction, this)); 
// or 
$(document).bind("customEvent", $.proxy(this, 'onCustomAction')); 
//...