backbone 本地存储添加两次

backbone local storage adding twice

您如何解决 backbone 本地存储添加两次的问题。

我正在为 mu 本地存储中的所有内容获取双倍值。 local storage也加了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 local-storage 的创建函数中的错误

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

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

您可以通过使用快速 non-cryptographic 散列作为 ID 来避免这种情况,因为如果您添加两个具有相同 ID 的模型,backbone 将执行 no-op。

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;
};

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