2

I wonder how to replace the bindWithEvent function 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'}));
1
  • please update with fix and turn into a community wiki for others to see as this question is being asked a lot lately Commented Nov 5, 2010 at 15:34

2 Answers 2

3
el.addEvent('click', function(event){
    myFunction(event, param1, param2); // can use .pass and bind this again
}.bind(this));

it's hard to explain why it got deprecated though.

example in a class context:

var foo = new Class({
    initialize: function(el) {
        document.id(el).addEvent('click', function(event){
            this.foo(event, "hello");
        }.bind(this));
    },
    foo: function(event, what) {
        console.log(event, this); // this is the class instance
        alert(what);
    }
});

new foo("foo");
7
  • I like that! But isn't the "this" context lost inside myFunction?
    – Savageman
    Commented Nov 5, 2010 at 14:49
  • not really. jsfiddle.net/dimitar/Ty5DJ - read my revised example. you can always use .pass when you call the function to change the scope... Commented Nov 5, 2010 at 15:28
  • What about if I need to pass a "what" param which is a var outside of the event handler document.id(el).addEvent('click', function(event){ ... }.bind(this));
    – aartiles
    Commented Nov 7, 2010 at 15:21
  • in the second example i pass on 'hello' - this can actually be a var from any scope you can reference or a provate var to the class, eg, this.name = 'foo' ... this.foo(event, this.name); etc etc. i don't see what the hold up is - the only real downside to bindWithEvent being gone is that it all looks less tidy. :( Commented Nov 7, 2010 at 15:31
  • Please check jsfiddle.net/2tcRU, this is my case. As you can see no matter which element you click, the alert is always "hello4"
    – aartiles
    Commented Nov 8, 2010 at 16:44
2

You should read the upgrade from 1.2 to 1.3 page: http://github.com/mootools/mootools-core/wiki/Update-from-1.2-to-1.3

This is what I came up with: http://jsfiddle.net/MBx2D/2/

2
  • I did it before and it didn't help me
    – aartiles
    Commented Oct 31, 2010 at 11:17
  • It isn't my case. I need to pass "this" as the scope for the event handler. Please check my solution.
    – aartiles
    Commented Nov 1, 2010 at 19:51

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