Backbonejs collection.create:如果出现错误,如何防止它添加项目?

如果在输入中发现错误,如何防止collection.create将项添加到其集合中?

HTML,

 

New monolog


Monologs

    骨干,

     var Status = Backbone.Model.extend({ initialize: function(){ }, validate: function(attrs, options) { if(attrs.text === '') alert("please enter some text"); }, url:"dummy.php", sync: function (method, model, options) { return $.ajax({ type: "POST", dataType: 'json', url: 'server.php', data: { text: this.get("text") } }); } }); var Statuses = Backbone.Collection.extend({ model: Status }); var NewStatusView = Backbone.View.extend({ events: { "submit form": "addStatus" }, initialize: function(options) { _.bindAll(this, 'addStatus', 'clearInput'); this.listenTo(this.collection, 'add', this.clearInput) ; }, addStatus: function(e) { e.preventDefault(); this.collection.create({ text: this.$('textarea').val() }); }, clearInput: function() { this.$('textarea').val(''); } }); var StatusesView = Backbone.View.extend({ initialize: function(options) { this.collection.on("add", this.appendStatus, this); }, appendStatus: function(status) { this.$('ul').append('
  • ' + status.escape("text") + '
  • '); } }); $(document).ready(function() { var statuses = new Statuses(); new NewStatusView({ el: $('#new-status'), collection: statuses }); new StatusesView({ el: $('#statuses'), collection: statuses }); });

    因此,当您点击提交按钮而不键入任何文本时,您会从模型中的此部分弹出错误,

     validate: function(attrs, options) { if(attrs.text === '') alert("please enter some text"); }, 

    但是,如何告诉集合存在错误并且不添加此空项目并且不在模型中触发 sync

    编辑:

    得到它以这种方式与collection.create一起工作……

    模型,

     validate: function(attrs, options) { if(attrs.text === '') { var message = "please enter some text"; alert(message); return message; } }, 

    视图,

     addStatus: function(e) { e.preventDefault(); var one = new Status({ text: this.$('textarea').val() }); if (!one.isValid()) { alert(one.validationError); } else { this.collection.create(one); } }, 

    它似乎工作正常除非它不是一个好方法或反对MVC模式?

    我不认为collection.create是正确的选择。

     addStatus: function(e) { e.preventDefault(); var status = new Status({"text": this.$('textarea').val()}) var error = status.valiate(); if(!error) { this.collection.add(status); } }, 

    也不是主干文档说这关于validate

    如果属性有效,请不要从validate返回任何内容; 如果它们无效,则返回您选择的错误。 它可以像要显示的字符串错误消息一样简单,也可以是以编程方式描述错误的完整错误对象。

    因此,您的validationfunction应该是固定的:

     validate: function(attrs, options) { if(attrs.text === '') { var message = "please enter some text"; alert(message); return message; } }, 

    Model's validate方法应返回error字符串,以便在发出警报时不会触发模型保存。

     validate: function(attrs, options) { if(attrs.text === ''){ alert("please enter some text"); return "Text is empty."; // OR proper error CODE } } 

    检查Backbone.Model validation方法。