views:

162

answers:

4

Is it possible to do this from within a class?

   $("#" + field).click(this.validate);

So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed.

A: 

Yes it is possible.

10 mins ago was writting a snipet because i had just that problem

$("div.myalarms_delete").click(function(){
 var mid = this.id;
 $("li#"+mid).fadeOut("fast");
});

the div.myalarms_delete also as the id I needed

fmsf
Fucking ugly but it works
Click Upvote
Well thanks :p actually thought it was a pretty and simple solution
fmsf
Can't it just be:$("li#"+this.id).fadeOut("fast");
Robert Grant
errr ID's should be unique.....if I understand this correctly, if not why not use $(this).fadeOut()
redsquare
one is a div the other is a li, it was just an example to show him that yest it worked what he wanted
fmsf
and yes it can be just $("li#"+this.id)
fmsf
Its just javascript which is ugly and forces us to do hacks like this, your solution is fine ;)
Click Upvote
+3  A: 

I am not sure about an easy way, but you can always go the closure route:

var that = this;
$("#" + field).click(function() {
    that.validate();
});
Andrey Shchekin
+1 b/c this avoids javascript's tricky binding issues.
Kip
A: 

From inside a class you're typically better off using the .find function.

var child = this.find('.someChildClass');
var child2 = this.find('#someChildId');
justin
+1  A: 

Is it possible to do this from within a class?

$("#" + field).click(this.validate);

“this.validate” is problematic. JavaScript does not have bound methods, so when you pass that reference, it is only pointing to a plain function. When called, ‘this’ will not be correctly set. See ALA for a fairly thorough discussion of the binding loss problem.

Some frameworks provide built-in method-binding functionality; jQuery does not, as it tends to concentrate more on closures than JavaScript objects. In any case, creating a binding wrapper using a closure is pretty simple; Andrey's answer is the usual approach for jQuery users.

The one thing to look out for with closures for event handlers (whether you are using jQuery or not) is that it tends to cause memory leaks in IE. For simple, short-lived web pages you may not care.

bobince