dk123
dk123

Reputation: 19690

javascript - jQuery mobile execute transition after function finish

I'm currently using the current bit of html for jQuery Mobile page transitions:

<a href="#page2" data-role="button" data-transition="flip" onclick="save()">page2</a>

The save() function here is something that saves the canvas on the current page.

It seems however the save() function runs asynchronously along with the page transition and hence at times the page transitions without having managed to fully save the information I wanted it to.

Is there a way to completely finish a function before jQuery Mobile executes the page transition?

--update--

Here's a jsFiddle example for all to play around with:

http://jsfiddle.net/nMR85/1291/

(notice the pagebeforechange firing before the save trigger in the console)

Upvotes: 0

Views: 285

Answers (1)

Karol
Karol

Reputation: 8053

Try with this solution:

var transition = false;

function save() {

    if(!transition) {
        var callback = function() {
            transition = true;
            $("a").click();
        };

        // your aynchronous code which will trigger callback after it finishes executing

        return false;
    }
    else {
        transition = false;
    }
}

First execution of this function will not trigger transition (return false prevents from executing every next event handler attached). Second execution will, but will not trigger sending. Of course putting transition variable into global context is not a good practice, but it's just an idea how you can cope with this problem.

Also I think that inside onclick (in HTML) you should have return save().


EDIT ACCORDING TO THE PROVIDED FIDDLE:

Playing with the fiddle I have changed a element a little bit:

<a id="goto_trigger" href="#p2" data-role="button" onclick="return save()">Go To Page 2 with return</a>

Also Script should looks like this:

$(document).bind('pagebeforechange', function(e, data) {
    console.log("pagebeforechange");
});

var transition = false;

function save() {
    if(!transition) {
        setTimeout(function(){
            alert("save trigger");
            transition = true;
            $("#goto_trigger").click();
        },3000);
        return false;
    }
};

Now it works as expected.

Upvotes: 1

Related Questions