jquery synchronous functions

本秂侑毒 提交于 2019-11-30 21:28:40

If your doSomething() function is doing something asynchronously (such as making an Ajax request) then you'll want to make doSomethingElse() the callback for that asynchronous request, rather than having it execute immediately after doSomething() returns.

jitter

Actually you can do what you want with jQuery (at least in some sense). It could be considered a little bit hacky but works flawless.

Just include an element in your page which you don't use for anything else. e.g. an empty div somewhere.

<div id="syncFnHolder"></div>

And then include the JS with your functions + the runMe function written by me.

function doSomething() { alert("First"); }
function doSomethingElse() { alert("Second"); }
function doSomethingElseThree() { alert("Third"); }

function runMe(fn, selec) {
    return function() {
        fn();
        setTimeout(function() {
            $(selec).dequeue("syncFnQueue");
        }, 1000);
    } 
};

var selector = "#syncFnHolder";
//add three functions to a queue
$(selector).queue("syncFnQueue", runMe(doSomething, selector));
$(selector).queue("syncFnQueue", runMe(doSomethingElse, selector));
$(selector).queue("syncFnQueue", runMe(doSomethingElseThree, selector));
//start first function in queue (FIFO) others are triggered automatically
$(selector).dequeue("syncFnQueue");

This would generate three alerts with a distance of 1s between them saying "First", "Second", "Third".

If you want no delay remove the setTimeout and just leave the call to $(selec).dequeue("syncFnQueue");.

If your functions need parameters e.g. doSomething(x,y,z) you need to adapt the runMe function to be a better partial and to construct the returned function differently. Check here or post new question.

javascript partial

Mangesh Borkar

You may want to do this....

function doSomething(callback) {
    // code for do some thing
    // now fire off the callback
    if (typeof callback === 'function') {
        callback();
    }
}

function doSomethingElse() {
}

doSomething(doSomethingElse);

The question is a bit vague.

If your functions have asynchronous bits to them, then use callbacks. That's what they are for.

If, however, you want to do aspect-oriented programming in JavaScript, take a look at jQuery-aop.

There's no way to enforce this explicitly per se, but one idea is to have doSomething() return a value that doSomethingElse() accepts as a parameter:

  retval = doSomething();
  doSomethingElse(retval);

that way at least you prevent somebody from calling doSomethingElse() without at least supplying the argument it needs... of course, whether they get that argument from calling doSomething() is another issue. But this is a start.

Idea lifted from Code Complete.

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