Hi,

> So i was wondering if my code could be optimized ?

Yes, you only need to do the binding once, and then you can reuse it.
There are actually several optimizations you can perform on that
code.  I'll take an iterative approach:

1. You don't need to bind your iteration function; Enumerable#each[1]
has a second parameter you can give it to set the context for the
iterator.  So (I also put in a missing closing parenthesis and
semicolon):

// Take 1
initialize : function() {
    $$('.poper').each(function(element){
        Event.observe
(element,'click',this._clicCase.bindAsEventListener(this));
    }, this);
}

2. As you suspected, you only hav to bind once

// Take 2
initialize : function() {
    var f = this._clicCase.bindAsEventListener(this);
    $$('.poper').each(function(element){
        Event.observe(element,'click',f);
    });
}

3. And you almost certainly don't need bindAsEventListener (you almost
never do[2]), you can use Function#bind[3]

// Take 3
initialize : function() {
    var f = this._clicCase.bind(this);
    $$('.poper').each(function(element){
        Event.observe(element,'click',f);
    });
}

4. AND you can ditch your iterator function entirely, because you can
use Enumerable#invoke[4]

// Take 4
initialize : function() {
    $$('.poper').invoke('observe', 'click', this._clicCase.bind
(this));
}

[1] http://prototypejs.org/api/enumerable/each
[2] 
http://proto-scripty.wikidot.com/prototype:tip-you-probably-don-t-need-bindaseventlistener
[3] http://prototypejs.org/api/function/bind
[4] http://prototypejs.org/api/enumerable/invoke

HTH,
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available

On May 27, 2:48 pm, grunk <roger.oliv...@gmail.com> wrote:
> Hi,
> I'm using bindAsEventListener in my classes like this :
> <code>
> initialize : function(){
>     $$('.poper').each(function(element){
>         Event.observe
> (element,'click',this._clicCase.bindAsEventListener(this)
>     }.bindAsEventListener(this));}
>
> </code>
>
> in the prototype doc we can read : <quote> you must remember that
> bindAsEventListener returns a fresh anonymous function that wraps your
> method. This means that every call to it returns a new function </
> quote>
> So i was wondering if my code could be optimized ?
> For exemple, if i have 40 elements with the class ".poper"  , is the
> bindAsEventListener calls will slow down my app ?
>
> Thank's :)
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptaculous@googlegroups.com
To unsubscribe from this group, send email to 
prototype-scriptaculous+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/prototype-scriptaculous?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to