【问题标题】:backbone local storage adding twice骨干本地存储添加两次
【发布时间】:2015-10-24 09:10:52
【问题描述】:

您如何解决添加两次的主干本地存储。

我在 mu 本地存储中的所有内容都获得了双倍值。本地存储也加了一个key number,key id序​​列乱序:

     drink: function() {
        var val = $('#new_booze').val();
        console.log(val);
        if (val === this.lastTitle) {
            return;
        }
        this.lastTitle = val;

        this.collection.create({
            boozeTitle: val,
            id: this.makeID(val)
        });
        this.collection.fetch({
            reset: true
        });
    },

【问题讨论】:

    标签: backbone.js local-storage


    【解决方案1】:

    这是主干本地存储创建功能中的错误

    create: function(model) {
      if (!model.id) model.set(model.idAttribute, guid());
      this.data[model.id] = model;
      this.save();
      return model;
    },
    

    设置 id 和保存,都会触发模型上的保存。

    您可以通过使用快速非加密哈希作为 id 来避免这种情况,因为如果您添加两个具有相同 id 的模型,主干将执行无操作。

    makeID: function(string) {
      var hash = 0;
      if(string.length === 0) {
         return hash;
      }
      for(i = 0; i < string.length; i++)
      {
        char = string.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash;
      }
     return hash;
    };
    

    这有一些缺点,因为它是一个哈希函数,每个标题只能添加一次,并且哈希冲突的可能性更大。

    【讨论】:

      猜你喜欢
      • 2015-07-20
      • 2013-09-24
      • 1970-01-01
      • 2012-06-07
      • 2012-10-23
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      相关资源
      最近更新 更多