Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

scope - Controlling the value of 'this' in a jQuery event

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use jQuery.proxy() with anonymous function, just a little awkward that 'context' is the second parameter.

 $("#button").click($.proxy(function () {
     //use original 'this'
 },this));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...