在Backbone.js中,可以通过两种方式来指定元素的el属性:全局el和通过对象传递el。
var AppView = Backbone.View.extend({
el: '#app-container',
initialize: function() {
this.render();
},
render: function() {
// 渲染视图的内容
this.$el.html('Hello Backbone!');
// 创建子视图
var subView = new SubView();
}
});
var SubView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
// 渲染子视图的内容
this.$el.html('Hello SubView!');
}
});
var appView = new AppView();
在上面的代码中,我们通过全局el属性指定了AppView视图的根元素为id为"app-container"的元素。在render方法中,我们渲染了AppView视图的内容,并创建了一个子视图SubView。由于SubView没有定义el属性,它会继承AppView的el属性,也就是使用了"#app-container"作为根元素。
var AppView = Backbone.View.extend({
initialize: function(options) {
this.el = options.el; // 通过对象传递el属性
this.render();
},
render: function() {
// 渲染视图的内容
this.$el.html('Hello Backbone!');
// 创建子视图
var subView = new SubView({el: '#sub-container'});
}
});
var SubView = Backbone.View.extend({
initialize: function(options) {
this.el = options.el; // 通过对象传递el属性
this.render();
},
render: function() {
// 渲染子视图的内容
this.$el.html('Hello SubView!');
}
});
var appView = new AppView({el: '#app-container'});
在上面的代码中,我们在创建视图的时候通过options对象传递了el属性,用来指定视图的根元素。在AppView中,我们通过options.el获取到传递的el属性,并将其赋值给视图的el属性。同样的,在SubView中也通过options.el获取到传递的el属性,并将其赋值给子视图的el属性。这样,每个视图都可以独立指定自己的根元素。