You can indeed simplify that a fair bit:
var myClass = Class.create({
initialize: function() {
var self = this;
// To demo that we keep the instance reference, set a
// property on the instance
this.message = "Hi there";
$('formid').getElements().invoke("observe", "blur", blurHandler);
function blurHandler() {
// `self` references our instance
// `this` references the element we're observing
self.validateEl(this);
}
},
validateEl: function(el){
// validate $(el) in here...
// note that because of the way we called it, within this function,
// `this` references the instance, so for instance:
this.foo(); // alerts "Hi there!"
},
foo: function() {
alert(this.message);
}
});
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 the initialize
function, I use a variable to point to this
because the variable will then be available to the closure. (I called it self
because that's a standard practice when aliasing this
for this reason.) The handler makes use of Prototype's native functionality of setting this
within an event handler to the element being observed. When we call validateEl
via the closure's self
reference, we're calling it as a member function as per normal, so within validateEl
, this
refers to the instance.
Speaking of named functions, your initialize
and validateEl
functions 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.