【发布时间】:2012-02-23 22:53:02
【问题描述】:
我正在使用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");,项目仍在添加到集合中
当发现错误时,我可以做些什么来阻止集合添加结果?
更新1 短期解决方案如下,它有效,但我不确定它是否是正确的做事方式
ok = val.set(colorname: $('#new_video_url').val())
if ok
@collection.create colorname: val.get("colorname");
更新2
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
现在index中的方法很简单
createCrayonId: (event) ->
event.preventDefault()
@collection.create colorname: $('#new_color_name').val()
【问题讨论】:
-
你的收藏是颜色的集合还是别的什么?
标签: ruby-on-rails backbone.js coffeescript