0

Backbone 中的get函数似乎没有成功回调。有没有办法延迟下面代码中视图的创建,直到我确定self.restaurant存在?

self.restaurant = app.collections.restaurants.get(id);
this.showView( '#main', new app.Views.RestaurantDetailView({model: self.restaurant }) );

我可以做这个

if (self.restaurant){
  this.showView( '#main', new app.Views.RestaurantDetailView({model: self.restaurant }) );

}else{ 

}

但如果 self.restaurant 不存在,那么我最终会做一些尴尬的事情来让它工作。我在想这个问题必须有一个我不知道的简单解决方案。

4

1 回答 1

0

Instead of calling get on the collection with the id, I rather created a new model with the id, and then called fetch on the model. Fetch takes a success callback so there's no issue of waiting until the query's finished before creating the view

 var restaurant = new app.Models.Restaurant({ id: id });
 var self = this;
 restaurant.fetch({
                success:function () {                           
                        self.showView( '#restaurants', new app.Views.RestaurantDetailView({model: restaurant}) );
                    }

        });
于 2013-09-12T16:04:38.267 回答