Я использую Backbone и Backbone LocalStorage плагин: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;
});
Было бы полезно увидеть полную реализацию плагина с вашей коллекцией. – srquinn