MooTools/JS: bindWithEvent

笑着哭i 提交于 2019-12-13 06:41:46

问题


There's this piece in the codebase I'm working on:

this.element.addEvent('click', this.clickEvent.bindWithEvent(this));

I want to change it so that the click event makes sure the window is loaded first. So I tried:

var t = this;
this.element.addEvent('click', function() {
    window.addEvent('load', function() {
        t.clickEvent.bindWithEvent(t));
    });
});

That doesn't seem to get it to work though. What am I missing?


回答1:


You're adding a handler to the load event when the user clicks something, _aftertheload` event has already fired. Therefore, nothing happens.

You should probably add the click handler inside of an event handler for the load event. (swap the two addEvent lines)




回答2:


in mootools you tend to use domready and not load but essentially, doing it as suggested will not work as it lacks the context here:

this.element.addEvent('click', this.clickEvent.bindWithEvent(this));

so you are working within a class here - therefore, make sure you instantiate it on the domready event instead, something like...

window.addEvent("domready", function() {
    // whatever you need to do...
    var foo = new myClass($("someElement"), {option: value}); // example instantiation
    // if the binding is not in the .initialize, then call the right method...
    // foo.bindMyEvents();
});

as long as the class instance is within domready, you're fine. if that's not an option, see which method binds the events and call that on the domready instead.



来源:https://stackoverflow.com/questions/1972235/mootools-js-bindwithevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!