Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否使localStorage中的Backbone.js项唯一?_Javascript_Backbone.js_Backbone Local Storage - Fatal编程技术网

Javascript 是否使localStorage中的Backbone.js项唯一?

Javascript 是否使localStorage中的Backbone.js项唯一?,javascript,backbone.js,backbone-local-storage,Javascript,Backbone.js,Backbone Local Storage,我在我的集合中有一个重复检查,我正在覆盖add函数,它似乎一直工作到页面刷新 重复项会被阻止,并显示“您已将此项添加到待办事项列表!”的警报,但似乎在页面刷新时,重复项会以任何方式添加到localStorage。我很想找到这个问题的解决方案——过去几天我一直在为这个问题挠头 我的收藏如下: app.TodoList = Backbone.Collection.extend({ model: app.Todo, localStorage: new Store("backbone-todo"

我在我的集合中有一个重复检查,我正在覆盖add函数,它似乎一直工作到页面刷新

重复项会被阻止,并显示“您已将此项添加到待办事项列表!”的警报,但似乎在页面刷新时,重复项会以任何方式添加到localStorage。我很想找到这个问题的解决方案——过去几天我一直在为这个问题挠头

我的收藏如下:

app.TodoList = Backbone.Collection.extend({
  model: app.Todo,
  localStorage: new Store("backbone-todo"),
  completed: function() {
    return this.filter(function(todo){
      return todo.get('completed');
    });
  },
  remaining: function(){
    return this.without.apply(this, this.completed());
  }
});

app.TodoList.prototype.add = function(todo) {

var isDupe = this.any(function(_todo){ return _todo.get('title').toLowerCase() === todo.get('title').toLowerCase();
});

return isDupe ? alert("You've already added this item to the todo list!") : Backbone.Collection.prototype.add.call(this, todo);}


// instance of the Collection
app.todoList = new app.TodoList();
模型如下:

  app.Todo = Backbone.Model.extend({
  defaults: {
    title: '',
    completed: false
  },
  toggle: function(){
    this.save({ completed: !this.get('completed')});
  }
});
观点:

  app.TodoView = Backbone.View.extend({
  tagName: 'li',
  template: _.template($('#item-template').html()),
  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    this.input = this.$('.edit');
    return this; // enable chained calls
  },
  initialize: function(){
    this.model.on('change', this.render, this);
    this.model.on('destroy', this.remove, this); // remove: 'Convenience Backbone'
  },
  events: {
    'dblclick label' : 'edit',
    'keypress .edit' : 'updateOnEnter',
    'blur .edit' : 'close',
    'click .toggle' : 'toggleCompleted',
    'click .destroy' : 'destroy'
  },
  edit: function(){
    this.$el.addClass('editing');
    this.input.focus();
  },
  close: function(){
   var value = this.input.val().trim();
   if(value) {
    this.model.save({ title: value });
   }
   this.$el.removeClass('editing');
  },
  updateOnEnter: function(e){
    if(e.which == 13){
      this.close();
    }
  },
  toggleCompleted: function(){
    this.model.toggle();
  },
  destroy: function(){
    this.model.destroy();
  }
});

// renders the full list of todo items calling TodoView for each one.
app.AppView = Backbone.View.extend({
  el: '#todoapp',
  initialize: function () {
    this.input = this.$('#new-todo');
    app.todoList.on('add', this.addAll, this);
    app.todoList.on('reset', this.addAll, this);
    app.todoList.fetch(); // Loads list from local storage
  },
  events: {
    'keypress #new-todo': 'createTodoOnEnter'
  },
  createTodoOnEnter: function(e){
    if ( e.which !== 13 || !this.input.val().trim() ) { // ENTER_KEY = 13
      return;
    }
    app.todoList.create(this.newAttributes());
    this.input.val(''); // clean input box
  },
  addOne: function(todo){
    var view = new app.TodoView({model: todo});

    $('#todo-list').append(view.
      render().el);

  },
  addAll: function(){
    this.$('#todo-list').html(''); // clean the todo list
    // filter todo item list
    switch(window, filter){
      case 'pending':
          _.each(app.todoList.remaining(), this.addOne);
          break;
        case 'completed':
          _.each(app.todoList.completed(), this.addOne);
          break;
        default:
          app.todoList.each(this.addOne, this);
          break;
    }
  },
  newAttributes: function(){
    return {
      title: this.input.val().trim(),
      completed: false
    }
  }
});
路由器:

app.Router = Backbone.Router.extend({
  routes: {
    '*filter' : 'setFilter'
  },
  setFilter: function(params){
    console.log('app.router.params = ' + params);
    window.filter = params.trim() || '';
    app.todoList.trigger('reset');
  }
})
和初始值设定项:

 app.router = new app.Router();
 Backbone.history.start();
 app.appView = new app.AppView();

如果需要更多信息,我们将乐意提供。谢谢

在主干网中,当您调用create时,会同时调用add和save。请阅读此处的来源:

因此,您阻止了添加操作,但在添加副本时仍会执行保存操作

您可以使用主干网的内置验证来完成您尝试执行的操作:

app.Todo = Backbone.Model.extend({
  defaults: {
    title: '',
    completed: false
  },
  initialize: function() {
    this.on('error', function(model, error) {
      alert(error);
    });
  },
  toggle: function(){
    this.save({ completed: !this.get('completed')});
  },
  validate: function(attrs, options) {
    if ( this.collection.isExistingTodoTitleOnOtherTodo(attrs) ) {
      return "You've already added this item to the todo list!";
    }
  }
});

app.TodoList = Backbone.Collection.extend({
  model: app.Todo,
  localStorage: new Store("backbone-todo"),
  completed: function() {
    return this.filter(function(todo){
      return todo.get('completed');
    });
  },
  remaining: function(){
    return this.without.apply(this, this.completed());
  },
  isExistingTodoTitleOnOtherTodo: function(attrs) {
    return this.any(function(todo) {
      var titleMatch = todo.get('title').toLowerCase() === attrs.title.toLowerCase();
      var idMatch = attrs.id === todo.id;

      return titleMatch && !idMatch;
    });
  }
});
顺便说一句,你的主干已经过时了,所以网站上的文档不能反映你可以在代码中做什么