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語句?