views:

56

answers:

3

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?

+3  A: 

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));
Rui Carneiro
of course! `event.element` is perfect in this scenario
seengee
Although it works, using `event.element` here is a lot more work than is required. Also, although you're safe with `blur` (because it doesn't bubble), you wouldn't want to do that with `click` or any event that *does* bubble, because `event.element` would return the bottommost element (which could be a `span`, an `em`, an `a`, etc.) that was clicked, *not* the element you're observing. Sometimes that's what you want, sometimes not.
T.J. Crowder
@TJ - good call on the bubbling - when you say that its more work than required do you mean that purely in comparison to your closure example?
seengee
@seengee: Closure or binding. But unless it's happening *a lot*, it doesn't really matter regardless. It's just that `event.element` does a couple of extra function calls you don't need if you can go direct, but we're talking a couple of calls vs. one or none, which compared to everything else happening around the event probably doesn't really matter. :-)
T.J. Crowder
+2  A: 

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.

T.J. Crowder
thanks for the info on named functions, that's well worth considering. In your example though i presumably would have scope issues if i needed to call another function from within the class within the validateEl function unless i first declared `self` outside the class
seengee
@seengee: No, you could do that with standard `this.foo` notation. Within `validateEl`, `this` will refer to the instance, because of the way we called it. When you make a function call via a property, as with `self.validateEl(...)`, it means "call `validateEl` and make `this` within the call equal to `self`". More here: http://blog.niftysnippets.org/2008/04/you-must-remember-this.html
T.J. Crowder
@seengee: I've updated the example to show that.
T.J. Crowder
@TJ - wow, thanks for all the detail. some really good information in there
seengee
@TJ - I may well use the other approach but i have learned a great deal from your answer so points to you :)
seengee
+2  A: 

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.

Alsciende
another approach i really like, thanks!
seengee