我正在使用 Backbone 和 Backbone LocalStorage 插件:
https://github.com/jeromegn/Backbone.localStorage
在将模型保存到集合中时,我似乎遇到了一些麻烦,所以我决定只使用集合来保存我的数据,但现在似乎我不能使用插件方法来删除记录。这是一个例子:
我添加到本地存储,这在我的 Backbone 扩展集合中
this.localStorage.create({id: nextPoint, date_stamped: new Date()});
请注意,我阅读的所有文档都没有提到我需要在这里使用的“localStorage”键。
接下来我尝试删除此密钥:
var previousRecord = this.localStorage.find({id:currentPoints});
this.localStorage.destroy(previousRecord);
返回错误:
TypeError: Cannot call method 'isNew' of null
这是模型
var PointModel = Backbone.Model.extend({
localStorage: new Backbone.LocalStorage("Points"),
defaults: {
date_stamped: new Date()
},
/*initialize: function() {
if(typeof this.id != 'number') {
this.id = 11;
this.date_stamped = new Date();
}
}*/
});
这里是收藏
var PointsCollection = Backbone.Model.extend({
model: PointModel,
localStorage: new Backbone.LocalStorage("Points"),
initialize: function() {
this.pointsCard = this.createPointsCard();
},
// Public Methods
getCurrentPoints: function() {
return this.localStorage.records.length;
},
addPoint: function() {
// get the current amount of points
var currentPoints = this.getCurrentPoints(),
nextPoint = currentPoints+1;
if(nextPoint > _c.totalPoints) {
return alert('Display error, reached limit');
}
// create
this.localStorage.create({id: nextPoint, date_stamped: new Date()});
},
removePoint: function() {
// this may not work for the animation
// maybe need to rethink this and add custom function to remove local
// storage value
var _this = this;
// bit of a weird way to do this, but Backbone localStorage plugin didn't
// seem to remove records very easily.
var currentPoints = this.getCurrentPoints();
// first clear all
this.localStorage._clear();
// then re add the original amount
var range = _.range(1,currentPoints);
_.each(range, function() {
_this.addPoint()
});
// should work this way
/*
var currentPoints = this.localStorage.records.length,
previousRecord = this.localStorage.find({id:currentPoints});
this.localStorage.destroy(previousRecord);
*/
},
removeAllPoints: function() {
this.localStorage._clear();
},
/*
createPointsCard takes values from the config to
make an array which has each point and its status for example:
{
id: [1-9],
reward: string(rewardTitle) | false
stamped: true | false
}
*/
createPointsCard: function() {
var _this = this;
// first create an array to hold the maximum number of points
var range = _.range(1, _c.totalPoints+1),
points = [];
_.each(range, function(point) {
var reward = _this._comparePointsNumberToReward(point);
points[point] = {
id: point,
reward: reward,
stamped: true
}
});
console.log(points)
return points;
},
// Private Methods
/*
loop through each reward and then check if the current
point has a reward.
return string(title) | false
*/
_comparePointsNumberToReward: function(point) {
var hasReward = false;
_.each(_c.rewards, function(reward) {
if(reward.pointsRequired === point) {
hasReward = reward.title;
}
});
return hasReward
}
});
return PointsCollection;
});