使用下面的结构,我成功地将数据从CollectionView传递到ItemView。但是当我尝试将相同的数据传递给子ItemView(并呈现数据)时,数据对象是未定义的。
有什么想法吗?下面是我尝试过的一种方法的代码。
var myView = Backbone.Marionette.CollectionView.extend({
itemView: myItemView,
initialize: function(options) {
this.model = options.model;
},
itemViewOptions: function(model,index){
return{
viewModel: this.model
}
}
});
var myItemView = Backbone.Marionette.ItemView.extend({
template: _.template(Template),
initialize: function(options) {
this.viewModel = options.viewModel;
},
onRender: function(options) {
// I thought the line below was a method for passing options from one ItemView into another.
var view = new mySecondItemView ({model: this.viewModel});
view.render();
var temp = this.$el["0"]['innerHTML'];
// The line below proves to my satisfaction that the ItemView is receiving the data model from the CollectionView
temp += this.viewModel.get("property_name");
this.$el["0"]['innerHTML'] = temp;
}
});
var mySecondItemView = Backbone.Marionette.ItemView.extend({
// And I thought I could set the viewModel in this function by assigning it the value of the model that was passed through the options.
initialize: function(options) {
this.viewModel = options.model;
},
// Finally I expect to be able to display information from the data model in the following way. The line below is what tips me off the the fact that viewModel in this second, sub-ItemView is undefined.
template: _.template('<p><%= this.viewModel.get("property_name") %></p>')
});
答案 0 :(得分:0)
使用下面的代码,我只通过声明属性名称就可以访问子ItemView中模型的属性,所以我只能写this.model.get("property_name")
而不是<%= property_name %>
。
var myView = Backbone.Marionette.CollectionView.extend({ /* Nothing changes here */ });
var myItemView = Backbone.Marionette.ItemView.extend({
template: _.template(Template),
initialize: function(options) {
this.viewModel = options.viewModel;
},
onRender: function(options) {
// This does indeed pass the data to the sub-ItemView
var view = new mySecondItemView ({model: this.viewModel});
view.render();
var temp = this.$el["0"]['innerHTML'];
// The line below pulls the HTML rendered in the sub-ItemView
temp += '<div class="content">'+view.$el['0']['innerHTML']+'</div>';
this.$el["0"]['innerHTML'] = temp;
}
});
var mySecondItemView = Backbone.Marionette.ItemView.extend({
// Display a property like so...
template: _.template('<p><%= property_name %></p>')
});