how to replace bindwithevent in mootools 1.3

2384 ワード

I need covert this code from mootools 1.2 to 1.3

var SomeClass = new Class({
 initialize: function (els) {
  for (var i = 0; i < els.length; i++) {
   els[i].addEvent('click',
    this.alert.bindWithEvent(this, [i, els[i].get('text')])
   );
  }
 },

 alert: function (event, index, text) {
  alert(
   index + ' -> ' + text + ' | ' +
   'x:' + event.page.x + ', y:' + event.page.y
  );
 }
});

Here is the working version (1.2) http://jsfiddle.net/9Pn99/
Here is my version for 1.3 http//jsfiddle.net/9Pn99/1/
EDIT: I figured out how to do it, with a closure. http://jsfiddle.net/9Pn99/4/

for (var i = 0; i < els.length; i++) {
    (function (j) {
        els[i].addEvent('click',
            function (e) {
                this.alert(e, j);
            }.bind(this)
        );
    }.pass([i], this))();
}

Is there a better solution?
EDIT2: I found another easy way:

els.each(function (el, i) {
    els[i].addEvent('click',
        function (e) {
            this.alert(e, i);
        }.bind(this)
    );
}, this);

Looks like I'm talking alone.
I wonder how to replace the bindWithEvent funtion in Mootools 1.3, the example in the documentation is very basic:

Element.addEvent('click', function(e){
myFunction.bind(bind, [e]);});

But, what about if I need to pass a param to the event handler? This is the way in Mootools 1.2:

Element.addEvent('click', function(e, param) { e.stop(); alert(param) }.bindWithEvent(this,['text']);

Any idea on how to replace this in Mootools 1.3.
Update: I found a very ugly solution, but a least it works while I find a built-in solution:

Element.addEvent('click', function(e){ e.stop(); this.bind.myFunc(this.param);}.bind({bind:this, param: 'text'}));

変換元:http://stackoverflow.com/questions/4062839/how-to-replace-bindwithevent-in-mootools-1-3