简体   繁体   中英

Using .bind (mootools) with onClick event

I have the code (inside one object) onclick: this._addX.bind(this) and then inside another object onclick: this._addY.bind(this)

Now, _addX() and _addY are nearly identical, except they both end up calling (on the click event) a function with different argument values, say _addX calls foo('x') and _addY calls foo('y'). So I tried:

onclick: this._add.bind(this,'x') and onclick: this._add.bind(this,'y') in the two objects. And of course I changed _add to accept an argument.

At runtime, when _add is called, it does not see any incoming arguments! I have fumbled around with different syntaxes but nothing works. Any ideas? The original syntax works fine (no arguments) but forces me to duplicate a large function with only one line different, which pains me. Thanks in advance.

_add: function(which) {
    var me = this;
    var checkFull = function(abk) {
        if (abk.isFull) {
            alert("full");
        } else {
        alert(which);  // which is always undefined here!
        }
    };
    getAddressBook(checkFull); //checkFull is a fn called by getAddressBook
},

this works and it keeps the scope within an element click event with the scope set to the class and not the element--there is no point in passing scope to the add method, it already has that:

var foo = new Class({
    Implements: [Options],
    add: function(what) {
        alert(what);
    },
    initialize: function(options) {
        this.setOptions(options);

        this.options.element.addEvents({
            click: function() {
                this.add(this.options.what);
            }.bind(this)
        });
    }
});

window.addEvent("domready", function() {
    new foo({
        element: $("foo"),
        what: "nothin'"
    });
});

just make an element with id=foo and click it to test (alerts nothin'). if your onclick is a function / event handler within your class as opposed to a normal element click event, then things are going to differ slightly - post a working skeleton of your work on http://mootools.net/shell/

If you read my previous answer, disregard it. The MooTools .bind method supports passing parameters. So something else isn't working as you expect:

onclick: this._add.bind(this, 'y');

Here is a simple setup on JSBin to show how bind truly does pass parameters.

The only purpose of bind is to "tell" the JS what object you mean when you say this . ie you pass as a parameter to bind an instance of the object you wish the this key word will refer to inside the function you used the bind on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM