Improve this snippet from a prototype class
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开发者_JS百科().invoke("observe","blur" ...
Not sure how i would pass the element references in though?
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.
I can't see nothing wrong with your code :)
About observers you can to something like this:
$('formid').getElements().invoke("observe","blur", function(e) {
this.validateEl(e.element());
}.bind(this));
I think that it will look slightly less verbose if you create a registerBlur
method:
var myClass = Class.create({
initialize: function() {
$('formid').getElements().each(this.registerBlur, this);
},
registerBlur: function(el) {
Event.observe(el, 'blur', this.validateEl.bind(this, el));
},
validateEl: function(el){
// validate $(el) in here...
}
});
But I agree with Rui Carneiro, I don't see anything wrong with your code either.
精彩评论