开发者

How to call an event handler dynamically and get its return value in javascript?

I asked a question yesterday, I accepted the answer, but sometime later, I came to know that the solution was not complete. The question is :-

Insert a JQuery click handler that executes before the ones already registered

using setTimeout(handler,0); returns immediately and I can not use return setTimeout(handler,0);. How can I run this handler synchronously and not allow the parent function to complete until this handler is completely executed and I get the return value out of it ?

I am in hurry, so I am asking it again, rather than editing that q开发者_运维百科uestion again.


You don't need to use setTimeout. If u don't use setTimeout, your handler reamins synchronous, and you can return all the value u want in your function.

<script>
   function f2() {
      alert('Handler declared in HTML')
   }

   buttons = document.getElementsByTagName('input');  // refine this, later

   for (i = 0, max = buttons.length; i < max; i++) {
      oldonclick = buttons[i].onclick;

      buttons[i].onclick = function() {
         alert('Prepend handler');
         oldonclick();
      }
   }
</script>


Since timeouts are asynchronous you’ll need to set the variable from within the timeout (and/or call a callback function).

var x = 1;

setTimeout(function() {
  x = 2;
}, 2000);

Here’s an example with a callback function. You need this is you want to do something with the variable as soon as it’s changed.

var x = 1;

function callback(x) {
  console.log(x);
}

setTimeout(function() {
  x = 2;
  callback(x);
}, 2000);

This will log 2 as soon as the timeout is executed.

Depending on what exactly it is you’re trying to do, you may not need timeouts at all, which avoids asynchronicity and a lot of trouble.


Quick answar: What about changing:

setTimeout(clickhandler, 0);

to

eval(clickhandler)();

to

eval(clickhandler);

$(document).ready(function() {
        $("input[type=button]").each(function() {

            // your button
            var btn = $(this);

            // original click handler
            var clickhandler = btn.data("events").click[0];
            btn.unbind("click", clickhandler);


            // new click handler
            btn.click(function() {
                alert('Prepended Handler');
                clickhandler();
            });
        });
    });

    function f2() {
        alert('Handler declared in HTML');
    }

And now clickhandler is a function, right?

See: jQuery: Unbind event handlers to bind them again later

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜