Search code examples
javascriptajaxbackbone.jshref

Delay href execution click until after ajax call


In a Backbone view, is it possible to delay the execution of a click on an anchor href until an ajax call was finished?

What I would require is:

  1. The user clicks an href;
  2. On click, an ajax call is triggered;
  3. If the ajax call is successful, only then should the href should be executed;

I did a test, adding a method to a Backbone view, linked to an anchor:

    clickNext: function(e){ 

        setTimeout(function(){
            console.log("test"); 
        }, 5000); 

Unfortunately, the href is executed before the timeout was finished.

The reason why I need this, is because I want to develop a wizard in which every page has a separate url; I perform checks with the localstorage on each pageload, and I perform a persistent storage (Ajax) on each "Next" click.


Solution

  • To prevent the original click triggering the location change use e.preventDefault() then you can use the done or success call back, when an ajax call has been successful,to manually change the window hash location.

    myApp.Views.ExampleView = Backbone.View.extend({
        el: "#myView",
        events: {
            "click a": "handleLink"
        },
        handleLink: function (e) {
            e.preventDefault();
            var link = $(e.currentTarget).attr('href');
            $.ajax("/echo/json/")
                .done(function () {
                location.hash = link
            })
        }
    });
    
    var myView = new myApp.Views.ExampleView();
    

    fiddle - http://jsfiddle.net/leighking2/hjcg77h2/