This is a snippet from a prototype class i am putting together. The scoping workaround feels a little hacky to me, can it be improved or done differently?
var myClass = Class.create({
initialize: function() {
$('formid').getElements().each(function(el){
$(el).observe("blur", function(){
this.validateEl(el);
}.bind(this,el));
},this);
},
validateEl: function(el){
// validate $(el) in here...
}
});
Also, it seems to me that i could be doing something like this for the event observers:
$('formid').getElements().invoke("observe","blur" ...
Not sure how i would pass the element references in though?
You can indeed simplify that a fair bit:
That uses
invoke(as you suggested) and a named function for the handler (doesn’t have to be named, but I find that it’s very helpful to have your functions have names). The handler is a closure. In theinitializefunction, I use a variable to point tothisbecause the variable will then be available to the closure. (I called itselfbecause that’s a standard practice when aliasingthisfor this reason.) The handler makes use of Prototype’s native functionality of settingthiswithin an event handler to the element being observed. When we callvalidateElvia the closure’sselfreference, we’re calling it as a member function as per normal, so withinvalidateEl,thisrefers to the instance.Speaking of named functions, your
initializeandvalidateElfunctions are both anonymous, which means on call stacks and such in debuggers, you’ll just see “(?)” rather than a nice, handy name. I always recommend actual named functions; more here.