骨干:在VIEW上显示集合中每个模型的验证错误 [英] Backbone: Show validation errors for each model in a collection on VIEW

查看:56
本文介绍了骨干:在VIEW上显示集合中每个模型的验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Backbone应用程序,允许用户添加多个项目.

I'm working on a Backbone application where I allow the user to Add multiple items.

这是我的型号:

//Model
    var Item = Backbone.Model.extend({
      defaults: {
        part1: 'hello',
        part2: 'world'
      },
      validate: function (attr, options) {
        var error = '';
        //console.log(attr);
        if(attr.part2 == "world1"){
          this.trigger('err:world1');
          error = 'world 1 error';
        }
        if(attr.part2 == "world3"){
          this.trigger('err:world3');
          error =  'world 3 error';
        }
      }
    });

收藏夹:

 //Collection
    var List = Backbone.Collection.extend({
      model: Item,

      validateModels: function() {
        var cloneCollection = this.clone();
        var errorModels = this.filter(function(m) {
          if (!m.isValid()) {
            return m;
          }
        });
        // cloneCollection.remove(errorModels);
        return cloneCollection;
      }
    });

我允许用户从视图中添加/删除项目:

I allow a user to Add/Delete items from the view as:

//Item View
    var ItemView = Backbone.View.extend({
      tagName: 'li', // name of tag to be created        

      events: {
        'click span.swap':  'swap',
        'click span.delete': 'remove'
      },    

      initialize: function(){
        _.bindAll(this, 'render', 'unrender', 'swap', 'remove'); // every function that uses 'this' as the current object should be in here

        this.model.bind('change', this.render);
        this.model.bind('remove', this.unrender);

        this.model.on('err:world1', this.world1Err);
        this.model.on('err:world3', this.world3Err);
      },

      render: function(){
        $(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> &nbsp; &nbsp; <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span> <span class="error" style="color:red; font-family:sans-serif;"></span>');
        return this; // for chainable calls, like .render().el
      },

      unrender: function(){
        $(this.el).remove();
      },

      swap: function(){
        var swapped = {
          part1: this.model.get('part2'),
          part2: this.model.get('part1')
        };
        this.model.set(swapped);
      },

      remove: function(){
        this.model.destroy();
      },

      world1Err: function(){
        alert('World 1 Err');
        //console.log(this);
      },

      world3Err: function(){
        alert('World 3 Err');
      }
    });

//Composite View
    var ListView = Backbone.View.extend({
      el: $('body'), // el attaches to existing element
      events: {
        'click button#add': 'addItem',
        'click  button#save': 'saveCollection'
      },

      initialize: function(){
        _.bindAll(this, 'render', 'addItem', 'appendItem'); // every function that uses 'this' as the current object should be in here

        this.collection = new List();
        this.collection.bind('add', this.appendItem); // collection event binder

        this.counter = 0;
        this.render();
      },

      render: function(){
        var self = this;
        $(this.el).append("<button id='add'>Add list item</button>");
        $(this.el).append("<button id='save'>SAVE</button>");
        $(this.el).append("<ul></ul>");
        _(this.collection.models).each(function(item){ // in case collection is not empty
          self.appendItem(item);
        }, this);
      },

      addItem: function(){
        this.counter++;
        var item = new Item();
        item.set({
          part2: item.get('part2') + this.counter // modify item defaults
        });
        this.collection.add(item);
      },

      appendItem: function(item){
        var itemView = new ItemView({
          model: item
        });
        $('ul', this.el).append(itemView.render().el);
      },

      saveCollection: function(){
        var collectionLength = this.collection.length;
        if(collectionLength > 0){
          this.collection.validateModels();
          //console.log(status);
        } 
        else
          alert('Collection is empty. Please add something.');
      }

    });

现在,当用户启动应用程序时,将向他/她显示屏幕:

Now when a user starts the application, he/she will be presented with the screen:

当用户单击添加"时,将添加项,如下所示:

When user clicks on Add, item would be added like:

我进行了硬编码验证,当用户单击 SAVE (保存)时,添加的第1个和第3个元素将返回错误.

I've put in hardcoded validation where 1st and 3rd added element would return error when user clicks on SAVE.

我被困住的地方是如何仅在特定项目视图中显示这些错误. 例如,如果第一第三项目存在错误,则模型会返回该错误,但我想将该错误映射到<仅strong>第一和第三列表项,如下所示:

Where I'm stuck is how do I show those error only at that particular item view. For instance, if there's an error at 1st and 3rd item, then the model returns that error but I want to map that error to the 1st and 3rd list-item only, much like this:

请帮助我提出解决方法.预先感谢!

Please help me suggest ways to approach it. Thanks in advance!

更新: 我已经找到了解决方案.因此,每当发生验证错误时,我都会执行以下操作:

UPDATE: I've found a fix to that. So whenever there's a validation error, I do something like this:

world1Err: function(){
        this.$el.find('span.error').text('Error Occured.')
      },

推荐答案

注意事项:

  • 请勿使用$(this.el),而应使用this.$el
  • 使用listenTo而不是on(绑定)来避免内存泄漏(的附加优点是,将使用侦听器作为上下文触发回调,在您的情况下为view )
  • 除非您知道自己在做什么,并且自己处理所有操作,否则不要覆盖Backbone.Viewremove方法
  • Don't use $(this.el), use this.$el instead
  • Use listenTo instead of on (bind) to avoid memory leaks (added advantage is that callbacks will be fired with the listener as context, in your case the view)
  • Do not override the remove method of Backbone.Viewunless you know what you're doing and handle all the things it does by yourself

明智的举动:

  • 使用主干事件哈希绑定的事件处理程序的默认上下文是视图本身,以及listenTo的使用,无需使用_.bindAll
  • Backbone集合具有许多内置的下划线方法,您可以改为this.collection.each_(this.collection.models).each
  • 您可以使用下划线,使用它的 template 方法,而不是手动生成模板
  • 您可以快速地 this.$(selector) 代替this.$el.find(selector)$(selector, this.el)
  • 无需手动创建模型实例,例如new Item(),将其设置为属性,然后将其添加到集合中,只需将属性传递给集合add方法,即可在内部创建模型实例
  • 您可以使用集合长度,而不必手动跟踪count属性
  • Default context of event handlers bound using backbone event hash is the view itself, along with the use of listenTo, no need to use _.bindAll
  • Backbone collection has lots of underscore methods built in, you can do this.collection.each instead of _(this.collection.models).each
  • You have underscore at your disposal, use it's template method rather than manually generating the template
  • You can quickly do this.$(selector) instead of this.$el.find(selector), $(selector, this.el) etc
  • No need to manually create an instance of model like new Item(), set it's attributes and then add it to collection, just pass the attributes to collections add method, it'll create a model instance internally
  • You can use the collections length instead of manually keeping track of the count property

建议:

  • 请勿使用内联样式
  • 让项目视图呈现其自身,并使用view.el而不是view.render().el(我真的不知道是谁发明了这种方式或原因)
  • Do not use inline styles
  • Have the item view render itself, and use view.el rather than view.render().el (I really don't know who invented this way or why)

您可以如下所示概括您的代码:

You can generalize your code as shown below:

var Item = Backbone.Model.extend({
  defaults: {
    message: 'hello world',
    count: 0
  },
  validate: function(attr, options) {
    if (attr.count % 2 != 0) {
      this.trigger('err', this.get('message') + attr.count + ' error');
    }
  }
});

var List = Backbone.Collection.extend({
  model: Item,
  validateModels: function() {
    this.each(function(m) {
      m.isValid(); // invoke models validate method
    });
  }
});

var ItemView = Backbone.View.extend({
  tagName: 'li',
  template: _.template($('#item').text()),
  events: {
    'click span.swap': 'swap',
    'click span.delete': 'remove' // triggers view's built in remove method
  },
  initialize: function() {
    this.listenTo(this.model, 'change', this.render);
    this.listenTo(this.model, 'err', this.errorHandler);
    this.render();
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  },
  swap: function() {
    var words = this.model.get('message').split(' ');
    this.model.set({
      message: words.reverse().join(' ')
    });
  },
  errorHandler: function(msg) {
    this.$('span.error').text(msg)
  }
});

var ListView = Backbone.View.extend({
  template: $('#itemView').text(),
  events: {
    'click button#add': 'addItem',
    'click  button#save': 'saveCollection'
  },
  initialize: function() {
    this.collection = new List();
    this.listenTo(this.collection, 'add', this.appendItem);
    this.render();
  },
  render: function() {
    this.$el.html(this.template);
    this.collection.each(function(model) {
      this.appendItem(model);
    }, this);
  },
  addItem: function() {
    this.collection.add({
      count: this.collection.length
    }, {
      validate: true
    });
  },
  appendItem: function(item) {
    this.$('ul').append(new ItemView({
      model: item
    }).el);
  },
  saveCollection: function() {
    if (this.collection.length > 0) {
      this.collection.validateModels();
    } else
      alert('Collection is empty. Please add something.');
  }
});
new ListView().$el.appendTo('body');

li span {
  font-family: sans-serif;
}
span.control {
  cursor: pointer;
}
span.swap {
  color: blue;
}
span.delete {
  color: orange;
}
span.error {
  color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
<script type="text/template" id="item">
  <span><%=message%> <%=count? count: ''%></span>
  <span class="swap control">[swap]</span>
  <span class="delete control">[delete]</span> 
  <span class="error"></span>
</script>
<script type="text/template" id="itemView">
  <button id='add'>Add list item</button>
  <button id='save'>SAVE</button>
  <ul></ul>
</script>

这篇关于骨干:在VIEW上显示集合中每个模型的验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆