开发者

bindWithEvent mootools 1.3

开发者 https://www.devze.com 2023-01-26 19:43 出处:网络
I need covert this code from mootools 1.2 to 1.3 var SomeClass = new Class({ initialize: function (els) {

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);
   开发者_JAVA百科         }.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.


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.


how to replace bindwithevent in mootools 1.3


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消