0

I have some code that cycles through each id and adds a character count handler. Because I needed to pass the id variable to the handler function, I needed to use this anonymous function with event.data.param1.

$('#comment_editor' + id).on("click dbclick mousedown mousemove mouseover mouseout mouseup keydown keypress keyup blur change focus select", {param1: id},
function (event) {
    comment_change(event.data.param1);
});

Paste and cut need a fix when adding a handler because they are delayed, so the handler needs to have a timeout before doing what it needs to do. Again, I need to pass the id variable to the handler, but I also need to pass it through the timeout. I set it up, but it doesn't work.

$('#comment_editor'+updates[i][0]).on("paste cut", {param1:id},
    function (event) {
        setTimeout(
            function (event) {
                comment_change(event.data.param1);
            }, 1);
    }
);
}

How can I get the past/cut handler to accept the id variable?

4

2 回答 2

3

Try removing event from function param you send to timeout:

$('#comment_editor' + id).on("paste cut",
    function (event) {
        setTimeout(
            function () {
                comment_change(event.data.param1, id);
            }, 1);
    }
);

That way your event will be 'inherited' from outer closure.

于 2013-06-29T22:52:26.273 回答
1

You cannot refer to id within the for, because when the handlers will be executed the id will always refer to the last value that was processed inside the loop.

Therefore should move the handler creation to another method like getHandlerFor(id). This way you can bind each one of the ids to the context of that method, and you'll be able to refer to the id directly from within the functions.

like:

var getHandlerFor = function (id) {
    return function (event) {
        setTimeout(
            function () {
                // use id without worries, since it has been bound to the context of this method.
                comment_change(event.data.param1);
            }, 1);
    };
};

/* ... */

for(var id in ids){
    $('#comment_editor' + id).on("paste cut", getHandlerFor(id));
}
于 2013-06-29T22:54:17.163 回答