public
Last active

What is Backbone's idiomatic way to create/save valid models?

  • Download Gist
backbone-question.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Backbone = require 'backbone'
 
Backbone.sync = ->
console.log 'Sync called.'
 
Book = Backbone.Model.extend
validate: ->
console.log 'Validate called.'
return "error"
 
Library = Backbone.Collection.extend
model: Book
 
lib = new Library
lib.create
title: 'A Book'
# Skips validate
 
(new Book { title: 'Another book.'}).save()
# Skips validate
 
book = new Book
book.save
title: 'A third book.'
# Runs validate, does not sync

Was surprised that save() without attrs bypasses validate. Is the recommended approach not setting with the constructor, but instead setting with set/save? Is there any way to enforce validation on Collection's create method?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.