gpt4 book ai didi

javascript - jQuery 访问带有事件和触发器的 'this' 对象

转载 作者:行者123 更新时间:2023-11-30 10:54:26 26 4
gpt4 key购买 nike

我有两个由主类编排的类,我想知道在这些类中触发事件时如何访问正确的“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。但是,我确实想在另一个中调用其中一个的行为。

执行此操作的最佳方法是什么?

最佳答案

您需要保留this 值,您可以通过多种方式做到这一点,jQuery 1.4+ 为您提供了$.proxy。方法,例如:

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

关于javascript - jQuery 访问带有事件和触发器的 'this' 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3009653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com