Backbone.js集合上的客户端验证

时间:2012-02-23 01:58:36

标签: ruby-on-rails backbone.js coffeescript

我正在使用backbone-on-rails gem并获得以下内容:

模型

class Crayons.Models.Color extends Backbone.Model
  validate: (attrs) ->
    if attrs.colorname.length == 0 
      return "colorname can't be empty"

集合

class Crayons.Collections.Color extends Backbone.Collection
  url: '/api/colors'

集合在路由器中创建

  initialize: ->
    @collection = new Crayons.Collections.Color()
    @collection.fetch()

ColorIndex中的方法

  createCrayonId: (event) ->
    event.preventDefault()
    val = new Crayons.Models.Color()
    val.on("error", @errorHandling);
    val.set(colorname: $('#new_color_name').val())
    @collection.create colorid: val.get("colorname");
    $('#new_color')[0].reset()

  errorHandling: (model, event) ->
    alert(event)

我有一个简单的验证,当长度为零时显示警报。但是,在警告框之后,由于@collection.create colorid: val.get("colorname");

,项目仍在添加到集合中

如果发现错误,我该怎么做才能阻止集合在其中添加结果?

UPDATE1 短期解决方案在下面并且有效,但我不确定它是否是正确的做事方式

ok = val.set(colorname: $('#new_video_url').val())
if ok
  @collection.create colorname: val.get("colorname");

UPDATE2

class Crayons.Collections.Colors extends Backbone.Collection
  url: '/api/videos'
  model: new Crayons.Models.Color()
  validate: (attrs) ->
    if attrs.colorname.length == 0 
      return "colorname can't be empty"

正确的方式 验证函数应该在模型中,并且应该在模型上初始化警告错误的函数。

class Crayons.Models.Color extends Backbone.Model
  initialize: -> 
    this.bind("error", @errorHandling)

  errorHandling: (model, event) ->
    alert(event)

  validate: (attrs) ->
    #your error validation goes here

现在索引中的方法非常简单

  createCrayonId: (event) ->
    event.preventDefault()
    @collection.create colorname: $('#new_color_name').val()

1 个答案:

答案 0 :(得分:2)

您的验证会触发颜色模型,但不会触发收集模型。因此,如果您想以干净的方式执行此操作,则应该为集合模型添加验证以检查colorId是否有效,与使用videoid的更新相同。

您可以设置集合的模型属性以及创建/保存集合模型的时间,它将使用此模型的验证来确定是否应该创建/保存模型

相关问题