Controlling the value of 'this' in a jQuer

2019-01-03 09:50发布

I have created a 'control' using jQuery and used jQuery.extend to assist in making it as OO as possible.

During the initialisation of my control I wire up various click events like so

jQuery('#available input', 
            this.controlDiv).bind('click', this, this.availableCategoryClick);

Notice that I am pasing 'this' as the data argument in the bind method. I do this so that I can get at data attached to the control instance rather from the element that fires the click event.

This works perfectly, however i suspect there is a better way

Having used Prototype in the past, I remember a bind syntax that allowed you to control what the value of 'this' was in the event.

What is the jQuery way?

8条回答
Rolldiameter
2楼-- · 2019-01-03 10:15

you can use the javascript bind method like this:

var coolFunction = function(){
  // here whatever involving this
     alert(this.coolValue);
}

var object = {coolValue: "bla"};


$("#bla").bind('click', coolFunction.bind(object));
查看更多
叼着烟拽天下
3楼-- · 2019-01-03 10:19

jQuery has the jQuery.proxy method (available since 1.4).

Example:

var Foo = {
  name: "foo",

  test: function() {
    alert(this.name)
  }
}

$("#test").click($.proxy(Foo.test, Foo))
// "foo" alerted
查看更多
登录 后发表回答