关于这种方法似乎有点......我继承了一个骨干项目,这就是路由的完成方式:
APP.routes.on("route:default", function( actions ) {
var url = some.api
jsonp.request(url,function(data){
var model= new mModel(data.someData);
var view = new MyView({model:model});
});
});
我想知道这是否是标准可接受的方法,或者如果不是更好的解决方案。我找不到任何人做这种架构的例子。完整的代码重构不是100%可行,但我想写一些关注点。我担心的是这里的模型和视图是紧密耦合的。这种模式重复30个左右的路线,都有自己的模型/视图配对。该应用程序还使用直接视图进行嵌套JSON请求,这是一个完全独立的问题。无论如何,该应用程序非常缓慢,我试图缩小原因,就像我说的,这看起来至少可以说是怀疑。
答案 0 :(得分:0)
如何正确使用Backbone的路由器引起争议,但通常你想尽快向用户提供内容,即使它只是一个加载器,因为它总比没有好。代码应该更像是:
APP.routes.on("route:default", function( actions ) {
var view = new MyView
view.render()
});
MyView.js
// Abstract away the model's logic into the view
var MyView = Backbone.View.extend({
el: '#main-content',
template: _.template( '<blah>Some template</blah>' ),
initialize: function(){
this.model = new mModel()
},
// The model needs data first, so just return a loader while we wait
render: function(){
this.model.fetch({
success: _.bind( this.onModelDoneFetching, this )
})
this.$el.html('<img class="loader" alt="Loading content" />')
return this
},
// the model has the data so we can render content now
onModelDoneFetching: function(){
this.$el.html( this.template( this.model.toJSON() ) )
}
})
如果您注意到jsonp
浮动而不是fetch
被使用,可能是因为您的应用的API不在同一个域中。在这种情况下,重写Backbone的内部AJAX方法本来是最好的。这样做会是这样的:
Backbone.ajax = jsonp
应用程序的缓慢可能不是由于UI - 很可能是跨源请求是性能滞后的地方。