首次点击元素时,事件不起作用,第二次点击按预期工作
命名空间:
var goose = goose || {
Models: {},
Views: {},
Collections: {},
Routes: {}
};
集合,我在其中使用过滤器进行数据处理:
goose.Collections.CollectionChannels = Backbone.Collection.extend({
model: goose.Models.ModelChannel,
localStorage: new Backbone.LocalStorage("Channels"),
fetch: function(options) {
// check if localStorage for this collection exists
if(!localStorage.getItem("Channels")) {
var self = this;
// fetch from server once
$.ajax({
url: 'json/channels.json'
}).done(function(response) {
$.each(response, function(i, item) {
self.create(item); // saves model to local storage
});
});
} else {
// call original fetch method
return Backbone.Collection.prototype.fetch.call(this, options);
}
},
byFilter: function(filter, value) {
var _this = this, f;
this.fetch({success: function() {
f = _this.filter(function(model) {
return model.get(filter) == value;
});
},
error:
function() {
alert("Ошибка, обновите страницу.");
}
});
return new goose.Collections.CollectionChannels(f);
}
});
查看,设置活动:
goose.Views.ViewСhannel = Backbone.View.extend({
id: "item",
template: _.template($("#news_item").html()),
initialize: function() {
this.listenTo(this.model, "change", this.render);
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
events: {
"click .favor" : "addToFavor"
},
addToFavor: function() {
this.model.set("favorite", !this.model.get("favorite"));
this.model.save();
}
});
初始化视图并在过滤后添加集合:
goose.Views.viewСhannels = new goose.Views.ViewСhannels({
collection: goose.Collections.collectionchannels.byFilter("cat", "news"),
el: ".news .content"
});