是否可以使用下划线或主干函数从另一个视图调用视图?我只想使用“历史记录”视图显示信息,但调用时遇到麻烦。
var CityModel = Backbone.Model.extend({
defaults: {
city: null,
nickName: null,
founded: null
}
});
var StudentCollection = Backbone.Collection.extend({
Model: CityModel
});
// This outputs the data when there is a click event
var History = Backbone.View.extend({
tagName: 'li',
template: _.template("<h2><%= city %></h2>"),
initialize: function(){
this.render();
},
render: function(){
this.$el.html(this.template(this.model));
$('.History').append(this.$el);
return this;
}
});
我想从名为ViewFunction的CityView函数click事件中调用历史记录视图
var myCityTemplate = '<h1 class= "displayInfo" name= "showCity"><%= city %></h1>';
var CityView = Backbone.View.extend({
tagName: "li",
template: _.template(myCityTemplate),
initialize: function(){
this.listenTo(this.model, 'change', this.render);
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
events:{
'click .displayInfo':'displayFunction'
},
displayFunction: function(){
// This is to find where city lives, check out the console.log without the innerHTML
// console.log(this.$el.find('h1[name= "showCity"]')[0].innerHTML);
CityName = this.$el.find('h1[name= "showCity"]')[0].innerHTML;
console.log(Cities.where({city: CityName}));
var myCity = Cities.where({city: CityName});
var CityHistory = new History({model: myCity});
}
});
我使用模型mycity调用“历史记录”视图,该模型是在我从click事件中获取数据后定义的。当我进行控制台登录时,我确实有数据。
var CityListView = Backbone.View.extend({
el: ".cities",
initialize: function(){
this.render();
},
render: function(){
this.$el.empty();
this.collection.each(function(places){
var MetropolisViewModel = new CityView({model: places});
this.$el.append(MetropolisViewModel.render().$el);
}, this);
}
});
var city1 = new CityModel({city: "Anaheim", nickName: "Disney", founded: "1840"});
var city2 = new CityModel({city: "Las Vegas", nickName: "Sinners", founded: "1889"});
var city3 = new CityModel({city: "New York", nickName: "City of hope", founded: "1750"});
var city4 = new CityModel({city: "Palm Springs", nickName: "Very hot", founded: "1849"});
var Cities = new StudentCollection([city1, city2, city3, city4]);
var myCityList = new CityListView({collection: Cities});
一切正常,唯一的问题是从cityView调用History视图,但似乎不起作用。我的目标是使用“历史记录”视图作为仅显示每个城市到HTML的数据的方式。
答案 0 :(得分:0)
我知道了,问题是当我使用
this。$ el.html(this.template(this.model)
在“历史记录”视图中,我将要显示的数据与从CityView中显示的数据(我使用的是
)相比格式不同this。$ el.html(this.template(this.model.toJSON()));
显示数据。因此,问题不在于调用视图,而是以不同的方式显示数据。不同的是,当我从模型中获取信息时,格式差异很大,以至于显示该数据时出现问题。因此,我使用了this。$ el.html(this.template(this.model [0] .attributes));在“历史记录”视图中以正确输出数据。