1

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.

1
  • on your last edit: els[i].addEvent should just be el.addEvent, otherwise, 100% on the money - i did not see your edit before i set out to do my answer :( deleting shortly. Commented Nov 23, 2010 at 21:11

3 Answers 3

1

The simplest solution is to reverse arguments in the method :) so if you have method like this

function (e, a){}.bindWithEvent(this, [i, els[i].get('text')])

do

function (a, e){}.bind(this, [i, els[i].get('text')])

because event is always the last argument.

0

how to replace bindwithevent in mootools 1.3

1
  • Based on that solution is I made this script: jsfiddle.net/9Pn99/3, what I need is pass the index to the event handler.
    – Luistar15
    Commented Nov 23, 2010 at 20:29
0

based upon what you posted: http://jsfiddle.net/dimitar/9Pn99/5/

var SomeClass = new Class({
    initialize: function (els) {
        els.each(function(el, i) {
            el.addEvent("click", function(e) {
                this.alert(e, i);
            }.bind(this));
        }, this);
    },

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

new SomeClass($$('li'));

each loops give you a natural run-time index you can display (as opposed to for loops that reference a single variable that ends up at a set value).

if you look at the mootools tag list, there are currently 3 or 4 questions on the first page on replacing bindWithEvent as well as 2 on echoing 'then' state of variables on looped elements. for the latter, you can also create closures and all sorts.

have fun :)

Not the answer you're looking for? Browse other questions tagged or ask your own question.