简体   繁体   English

延迟href执行单击,直到ajax调用之后

[英]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? 在骨干视图中,是否可以将对锚href的单击的执行延迟到ajax调用完成之前?

What I would require is: 我需要的是:

  1. The user clicks an href; 用户单击href。
  2. On click, an ajax call is triggered; 点击时,会触发ajax调用;
  3. If the ajax call is successful, only then should the href should be executed; 如果ajax调用成功,则只有应执行href;

I did a test, adding a method to a Backbone view, linked to an anchor: 我做了一个测试,在链接到锚点的Backbone视图中添加了一个方法:

    clickNext: function(e){ 

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

Unfortunately, the href is executed before the timeout was finished. 不幸的是,href是在超时结束之前执行的。

The reason why I need this, is because I want to develop a wizard in which every page has a separate url; 之所以需要它,是因为我想开发一个向导,其中每个页面都有一个单独的URL。 I perform checks with the localstorage on each pageload, and I perform a persistent storage (Ajax) on each "Next" click. 我对每个页面加载都使用localstorage进行检查,并且对每个“下一步”单击都执行持久性存储(Ajax)。

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. 为防止原始单击触发位置更改,请使用e.preventDefault()然后在ajax调用成功后,可以使用完成或成功回调来手动更改窗口哈希位置。

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/ 小提琴-http: //jsfiddle.net/leighking2/hjcg77h2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM