0

Я использую 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; 
}); 
+0

Было бы полезно увидеть полную реализацию плагина с вашей коллекцией. – srquinn

ответ

1

Backbone.LocalStorage плагин заменяет Backbone.sync глобально или по sync методу коллекции с store.js, реализации х-браузера из LocalStorage. Он также ТОЛЬКО работает над коллекциями, а не с моделями. Вы не должны создавать любые методы CRUD для взаимодействия с LocalStorage как плагин использует нативный сохранить, принесите и т.д.

С учетом сказанным, я думаю, что ваша главная ошибка приходит от этого: Коллекции должны распространяться Backbone.Collection, не Backbone.Model

var PointsCollection = Backbone.Model.extend({}); 
// Should be 
var PointsCollection = Backbone.Collection.extend({}); 

Поскольку вы используете модели, то LocalStorage плагин не используются должным образом (она работает только на сборниках) и, таким образом, ваша потребность сверлить в цепочку прототипов, чтобы получить доступ к объекту LocalStorage.

+0

Не могу поверить, что я этого не заметил !!! Большое спасибо. –

+0

Мы все это делаем! Я часами показывал код, чтобы друг заглянул мне через плечо и увидел ошибку в 30-х годах. – srquinn

Смежные вопросы