Mic*_*ael 7 backbone.js backbone-views
我有一个加载子视图的骨干视图.当我加载子视图时,我想在视图获取所需数据时显示加载器,并在视图准备好渲染时隐藏加载器.
我做了这样的事情:
var appView = Backbone.View.extend({
showLoader: function() {
// Code to show loader
},
hideLoader: function() {
// Code to hide loader
},
loadSubView: function() {
this.showLoader();
var myView = new MySubView();
this.$el.html(myView.render().el);
this.hideLoader();
}
});
Run Code Online (Sandbox Code Playgroud)
现在,我的子视图加载一个集合,并实现如下:
var mySubView = Backbone.View.extend({
initialize: function() {
this.myCollection.fetch({
async: false
});
},
render: function() {
// Code to render
}
});
Run Code Online (Sandbox Code Playgroud)
我的子视图同步加载集合,因为这是我发现知道什么时候我的视图"准备"渲染的唯一方法,但我认为这不是使用Backbone的最佳方式.
我该怎么办?
the*_*heo 15
有几种方法可以做到这一点.
您可以显式使用pubsub模式.像这样的东西:
var AppView = Backbone.View.extend({
showLoader: function() {
console.log('show the spinner');
},
hideLoader: function() {
console.log('hide the spinner');
},
loadSubView: function() {
this.showLoader();
var subView = new SubView();
subView.on('render', this.hideLoader);
this.$el.html(subView.render().el);
}
});
var SubView = Backbone.View.extend({
render: function() {
console.log('a subView render');
this.trigger('render');
return this;
}
});
var appView = new AppView({el: $('body')});
appView.loadSubView();
Run Code Online (Sandbox Code Playgroud)
您可以将函数附加到微调器本身的ajaxStart/ajaxStop事件:
var AppView = Backbone.View.extend({
initialize: function() {
var _this = this;
this.$('#spinner')
.hide()
.ajaxStart(_this.showLoader)
.ajaxStop(_this.hideLoader);
}
...
}
Run Code Online (Sandbox Code Playgroud)或者您可以使用jQuery.ajaxSetup:
var AppView = Backbone.View.extend({
initialize: function() {
var _this = this;
jQuery.ajaxSetup({
beforeSend: _this.showLoader,
complete: _this.hideLoader,
success: function() {}
});
}
...
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
10773 次 |
| 最近记录: |