Dealing with clash between jQuery and Object's

2019-07-31 02:59发布

I'm instantiating an Object which creates a DOM element and stores a jQuery Object as one of it's properties, e.g.:

this.element = $("<div></div>");

I noticed that when establishing events, jQuery's rewriting of thethis context can cause issues, such as if you tried to apply the following:

this.element.click(function() {
  this.someObjectMethod();
});

The inner this now applies to the DOM element and not the original Object. To overcome this, I can do the following:

var _this = this;
this.element.click(function() {
  _this.someObjectMethod();
});

I'm wondering, is bad practice and is there a better way? I've looked at some jQuery docs on apply and call but I'm not sure they'd help in this situation.

Additionally, I'm using Resig's 'simple inheritence 'Class, which might make a difference to your answers.

Update on seeing the $.proxy answers, these seem reasonable solutions, however you then lose the ability to reference the DOM element.

标签: jquery oop
1条回答
Emotional °昔
2楼-- · 2019-07-31 03:24

You can use $.proxy():

this.element.click($.proxy(function() {
    this.someObjectMethod();
}, this));

It returns a function that will always be invoked in the context of the object you specify in the second argument (in our case, the outer this).

$.proxy() also enforces a special case with event handlers: if you pass the original, unproxied method to off() or unbind() later, the proxied handler will be transparently removed even though you did not specify it directly.

查看更多
登录 后发表回答