当我们使用Backbone Model.fetch()从服务器上获取数据时,它默认会向服务器发送一个GET请求,并将从服务器上返回的数据注入到Model实例中。
当我们多次调用Model.fetch()时,可能会出现重复数据的情况。这时,需要在服务器端进行解决,或者在客户端使用缓存来避免重复数据的获取。
下面是一个使用缓存来避免重复数据获取的示例代码:
var MyModel = Backbone.Model.extend({ urlRoot: '/api/items',
initialize: function() { this.listenTo(this, 'sync', this.removeDuplicates); },
removeDuplicates: function() { var isNew = !(this.collection && this.collection.get(this.id));
if (isNew) {
if (this.collection) {
this.collection.add(this);
}
} else {
this.trigger('destroy', this);
}
} });
var MyCollection = Backbone.Collection.extend({ model: MyModel,
url: '/api/items',
getOrFetch: function(id) { var model = this.get(id);
if (!model) {
model = new MyModel({id: id});
this.add(model);
model.fetch();
} else {
model.fetch();
}
return model;
} });
var myCollection = new MyCollection(); var myModel = myCollection.getOrFetch(1); // 第一次获取 var myModel = myCollection.getOrFetch(1); // 第二次获取,使用缓存