Backbone fetch,promise and if else.它们是如何工作的

Backbone fetch, promises and if else. how do they work?

本文关键字:何工作 工作 promise fetch and if else Backbone      更新时间:2023-09-26

我有一个问题,我不知道如何在主干应用程序中巧妙地解决。我有一个视图,需要提取2个或3个不同的模型。

我有一个概要文件视图,它向客户显示他的任务和概要文件信息,但当coach访问它时,我还想加载coach模型,使coach能够切换内容。

承诺与if-else语句的关系如何?我可以用我写的方式写代码吗?它是这样工作的吗?

var tasks = new App.Task.Collections.Tasks();
var coaches = new App.Coach.Collections.Coaches();
var user = new App.User.Models.User();
if(App.User.Models.currentUser.isCoach()){
    var userPromise = user.fetch();
    var coachPromise = coaches.fetch();
    var tasksPromise = tasks.fetch({
        data: {
            userId: userdId
        }
    });
    $.when(userPromise, coachPromise, tasksPromise).then(function(){
        App.Layout.page.show(layout);
    });
}else{
    var userPromise = user.fetch();
    var tasksPromise = tasks.fetch({
        data: {
                userId: userdId
        }
    });

    $.when(userPromise, tasksPromise).then(function(){
        App.Layout.page.show(layout);
    });
}

承诺如何与if-else语句配合使用?

您的代码看起来是正确的。代码中的if/else语句不会影响所有的promise,因为在它们对应的块中有所有的.fetch()调用。只需记住将所有这些集合传递到要显示的布局即可。

您可以在Array上收集承诺,然后在时将其传递给$

var promises = [];
promises.push( modelA.fetch() ); // default
if(value){ 
   promises.push( modelB.fetch() ); // conditionally added
}
$.when.apply($, promises).then(function(){
   // do your stuff
});