Backbone LocalStorage模型和集合

时间:2013-12-11 15:49:37

标签: javascript backbone.js local-storage backbone-local-storage

我正在使用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;
});

1 个答案:

答案 0 :(得分:1)

Backbone.LocalStorage插件全局替换Backbone.sync,或者使用sync方法替换集合的store.js方法,Backbone.Collection是LocalStorage的x浏览器实现。它也仅适用于集合,而不适用于模型。你不应该构建任何与LocalStorage交互的CRUD方法,因为插件使用本机save,fetch等。

话虽如此,我认为你的主要错误来自于此:集合应该扩展Backbone.Model,而不是var PointsCollection = Backbone.Model.extend({}); // Should be var PointsCollection = Backbone.Collection.extend({});

{{1}}

因为您正在使用模型,所以LocalStorage插件未正确使用(它仅适用于集合),因此您需要深入到原型链中以获取对LocalStorage对象的访问权。