1
代码:如何使用localstorage自动保存主干中的更改?
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'
当与Backbone.localstorage页面加载时,控制台提供:
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
当我注释掉@bind电话,我得到预期:
init
test
new
我还可以在a
已加入sessions
并致电a.save()
后手动成功保存。
我想这个问题是会话构造触发change
事件,save()
不知道做什么之前a
已添加到sessions
?所以我可以做这样的事情:
class Session extends Backbone.Model
set: (fields, ops) ->
super fields, ops
if (this has been added to a Collection)
@save()
这是最好的方法吗?如果是,我如何填写if语句?