Code:
class Session extends Backbone.Model
initialize: ->
@bind 'change', @save
console.log 'init'
class SessionList extends Backbone.Collection
model: Session
localStorage: new Store 'sessions'
sessions = new SessionList
a = new Session x: 'test'
sessions.add a
console.log a.get 'x'
a.set x: 'new'
console.log a.get 'x'
When loaded in a page with Backbone.localstorage, the console gives:
init
test
Uncaught TypeError: Cannot read property 'localStorage' of undefined
backbone-localstorage.js:70
Backbone.sync
_.extend.save
backbone-localstorage.js:70
Backbone.Events.trigger
backbone.js:304
_.extend.change
backbone.js:117
And when I comment out the @bind call, I get the expected:
init
test
new
I can also save manually successfully after a has been added to sessions with a call to a.save().
I guess the problem is that the Session constructor triggers the change event, and save() doesn’t know what to do before a has been added to sessions? So I could instead do something like this:
class Session extends Backbone.Model
set: (fields, ops) ->
super fields, ops
if (this has been added to a Collection)
@save()
Is this the best way to do it? If yes, how do I fill in the if statement?
My suggestion would be to just call save instead of set. so replace this:
a.set x: 'new'with
a.save x: 'new'hope that works for you