开发者

jQuery access to 'this' object with events and triggers

I have two classes orchestrated by a main class and I would like to know how to gain access to the correct 'this' object when events are fired among these classes. Here's what I have:

// 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'. 
 开发者_StackOverflow社区   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]);
        }
    });
};

I don't want to merge ChildWorkerOne and ChildWorkerTwo because they are two separate entities that don't belong together and MainClass conceptually should orchestrate the ChildWorkerOne and ChildWorkerTwo. However, I do want to invoke the behavior of one in the other.

What's the best way to go about doing this?


You need to persist the this value, you can do it in many ways, jQuery 1.4+ provides you the $.proxy method, e.g.:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜