2011-05-31 92 views

回答

0

有主幹一些驗證插件,但我不喜歡這樣,我結束了這一點:

... 
validate: (attrs) -> 
    helper = @validationHelper attrs 
    helper.check 'name', (v) -> "can't be blank" if _(v).isBlank() 
    helper.check 'version', (v) -> "can't be blank" if _(v).isBlank() 
    helper.check 'organization', (v) -> "can't be blank" if _(v).isBlank() 
    helper.errors() 
... 

而這裏的幫手:

_(Backbone.Model.prototype).extend 
    validationHelper: (attrs) -> 
     helper = 
     _errors: {} 
     check: (name, validator) -> 
      return unless attrs and (name of attrs) 
      msg = validator attrs[name] 
      (@_errors[name] ?= []).push msg if msg 
      @ 
     errors: -> if _(@_errors).any() then @_errors else null 
     return helper