我有一个Backbone视图,预计会使用Select2呈现选择输入。
Select2Cell = Backbone.View.extend({
tagName: "select",
initialize: function(options) {
this.data = options.data;
},
render: function() {
this.$el.select2({data: this.data});
return this;
}
});
我正在另一个视图的render()
内呈现此视图:
CellsContainerView = Backbone.View.extend({
render: function() {
var view = new Select2Cell({data: [{id: 1, text: "Item 1"}]});
this.$el.append(view.render().$el);
return this;
}
});
问题是,当我渲染CellsContainerView
时,它不会显示select2。
$(document).ready(function() {
var containerView = new CellsContainerView({el: "#container"});
containerView.render();
});
答案 0 :(得分:0)
这个答案是在OP修复他的代码中的拼写错误之前编写的。
Select2 data需要是数组。您传递的是无效数组,请注意缺少的括号{}
:
[id: 1, text: "Item 1"]
因此,传递给选择视图的选项应更改为:
{ data: [{ id: 1, text: "Item 1" }]}
以下是修复代码的演示:
var Select2Cell = Backbone.View.extend({
tagName: "select",
initialize: function(options) {
this.data = options.data;
},
render: function() {
this.$el.select2({
data: this.data
}); // there was also a missing closing brace here
return this;
}
});
var CellsContainerView = Backbone.View.extend({
render: function() {
var view = new Select2Cell({
data: [{
id: 1,
text: "Item 1"
}]
});
this.$el.append(view.render().el);
return this;
}
});
var containerView = new CellsContainerView({
el: "#container"
});
containerView.render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<div id="container"></div>