[英]Render Backbone view dynamically
I have the following Backbone View : 我有以下骨干网视图:
var MyView = Backbone.View.extend({
id : 'myview'+atrs.i, //i is the property of atrs passed as parameter to view
initialize: function(atrs) {
$('#'+atrs.DOMid).append(this.$el);
}
});
I am considering that a HTML Element with id DOMid
already exists in Body before initialising the View. 我正在考虑在初始化视图之前,Body中已经存在ID为DOMid
的HTML元素。 Then I initialise the view as : 然后,将视图初始化为:
new MyView({DOMid:'mydiv',i:2});
But I get the error : cannot read property i of undefined
但我得到一个错误: cannot read property i of undefined
I also tried : 我也尝试过:
var MyView = Backbone.View.extend({
initialize: function(atrs) {
this.id = 'myview'+atrs.i;
$('#'+atrs.DOMid).append(this.$el);
}
});
In this case view is generated but with no any id attribute in it. 在这种情况下,将生成视图,但是其中没有任何id属性。
How do i approach my objective. 我如何实现我的目标。
If you want to set MyView's id dynamically, you'll have to use a function: 如果要动态设置MyView的ID,则必须使用一个函数:
id: function() { return 'myview'+atrs.i; },
But a cleaner approach would be to use the MyView's designated args on instantiation: 但是更干净的方法是在实例化时使用MyView的指定参数:
new MyView({el:'#mydiv',id:'myview2'});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.