我想先用主干渲染一个视图。显示从服务器中提取的文章的js。然后我想将其标记为“已看到”,并将未看到消息的计数返回给路由器,因为它需要提供给其他视图。
所以在我的路由器中,我有:
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()是:
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);
},
});
},
这会点击REST API,记录文章的查看情况,然后返回未查看文章的计数。这将导致控制台输出:
在什么时候和数据是路由器。js:286未定义的路由器。js:287英寸
saveView()成功与否取决于文章。js:45 4
所以,不知怎的,
$.when
在执行之前,它没有等待Ajax请求发送,因此不起作用
.done
剧本有什么想法吗?