Javascript 主干集合视图url触发两次
因此,我下面的应用程序在加载页面时,实际上在控制台中触发了两次“FIRE!”。我不知道为什么主干网会两次启动url函数,而我只看到一次抓取。你知道为什么这会导致它两次开火吗Javascript 主干集合视图url触发两次,javascript,jquery,backbone.js,Javascript,Jquery,Backbone.js,因此,我下面的应用程序在加载页面时,实际上在控制台中触发了两次“FIRE!”。我不知道为什么主干网会两次启动url函数,而我只看到一次抓取。你知道为什么这会导致它两次开火吗 window.ScheduleApp = { Models: {}, Collections: {}, Views: {} }; window.template = function(id) { return _.template($(
window.ScheduleApp = {
Models: {},
Collections: {},
Views: {}
};
window.template = function(id) {
return _.template($('#' + id).html());
};
//Define the Game Model.
ScheduleApp.Game = Backbone.Model.extend({
initialize: function() {
this.gameId = this.get('Id');
this.gameTime = this.get('Time');
}
});
//Define the Games Collection that contains Game Models.
ScheduleApp.Games = Backbone.Collection.extend({
model: ScheduleApp.Game
});
//Define the Day Model.
ScheduleApp.Day = Backbone.Model.extend({
initialize: function() {
this.games = new ScheduleApp.Games(this.get('Games'));
this.games.parent = this;
this.gameDayGDT = this.get('GeneratedDateTime');
this.gameDayDate = this.get('Date');
}
});
//Define the Days Collection that contains the Day Models.
ScheduleApp.Days = Backbone.Collection.extend({
model: ScheduleApp.Day,
url: function() {
console.log('FIRE!');
return '/js/test.json'
},
parse: function(data) {
var parsedSchedule = JSON.parse('[' + data.STUFF + ']');
return parsedSchedule;
}
});
ScheduleApp.DayCollectionView = Backbone.View.extend({
el: '.container', //Container where the views get rendered to.
initialize: function() {
this.listenTo(this.collection, 'reset', this.render);
},
render: function(event) {
if (this.collection.length === 0) {
$('.container-hidden').show();
}
//Cycle through collection of each day.
this.collection.each(function(day) {
var dayView = new ScheduleApp.DayView({
model: day
});
this.$el.append(dayView.render().el);
}, this);
return this;
}
});
ScheduleApp.DayView = Backbone.View.extend({
tagName: 'div',
className: 'game-date',
template: _.template($("#gameSchedule").html(), this.model),
initialize: function() {
this.listenTo(this.model, "reset", this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var daysList = new ScheduleApp.Days();
daysList.fetch({
reset: true,
update: true,
cache: false,
success: function(collection, response) {
//console.log(collection);
},
error: function(model, resp) {
// console.log('error arguments: ', arguments);
// console.log("error retrieving model");
}
});
//create new collection view.
var daysCollectionView = new ScheduleApp.DayCollectionView({
collection: daysList
});
如前所述,属于集合的所有模型都基于集合URL构建其URL。我猜您的集合只调用了一次该方法,然后您的模型进行第二次调用,以便构建模型URL
再说一次,这个方法对我来说似乎是无害的:它只是一个getter。我宁愿将
console.log
调用放在Collection\parse
或Model\initializer
方法中,并计算它在那里被调用的次数。您可以通过替换console.log('FIRE!')得到更好的主意代码>带有console.log(新错误().stack)代码>似乎集合#parse被触发一次。那么你是说url被触发两次是无害的吗?无害的意思是该方法只返回一个字符串(实际上可以将其设置为变量,不需要函数)。第二次调用的原因可能是模型构建了自己的URL,正如我在主干文档中指出的那样。