for .ajax .when,$.when not waiting for Ajax request to finish

问题

I want to first render a view with Backbone.js that displays an Article pulled from the server. I then want to mark this as "seen" and return the count of unseen messages to the router as it needs to be made available to other views.

So in my Router, I have:

getArticle: function (id) {

require(["app/models/article", "app/views/Article"], function (models, Article) {

var article = new models.Article({id: id});

article.fetch({

success: function (data) {

var articleView = new Article({model: data, message_count:that.message_count});

slider.slidePage(articleView.$el);

$.when(articleView.saveView()).done(function(data){

console.log('in when and data is ');

console.log(data);

});

},

error: function(){

console.log('failed to fecth artcie');

}

});

});

},

saveView() in the Article view is:

saveView: function(){

var viewDetails = [];

viewDetails.device_id = this.options.device_id;

viewDetails.article_id = this.model.id;

viewDetails.project_title = project_title;

var article_view = new models.ArticleView();

article_view.save(viewDetails,

{

success: function(data) {

var count = data.get('count');

console.log('in saveView() success and count is ');

console.log(count);

return count;

},

error: function(model, xhr, options){

console.log(xhr.responseText);

},

});

},

This hits a REST API, records the viewing of the article and then returns a count of unseen Articles. This results in a console output of:

in when and data is router.js:286 undefined router.js:287 in

saveView() success and count is Article.js:45 4

So, somehow, $.when is not working as it's not waiting for the Ajax request to send before executing the .done script. Any ideas?

回答1:

You need to return a jQuery Deferred object for $.when to work properly:

return article_view.save(viewDetails,

{

success: function(data) {

var count = data.get('count');

console.log('in saveView() success and count is ');

console.log(count);

return count;

},

error: function(model, xhr, options){

console.log(xhr.responseText);

},

});

Backbone's save() method returns a jqXHR object which behaves the same way as a Deferred object in this case. Simply chain the return call as above. This should get $.when() to wait for the request to finish.

来源:https://stackoverflow.com/questions/21405765/when-not-waiting-for-ajax-request-to-finish

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值