如何使用localstorage自动保存Backbone的更改?

时间:2011-12-22 21:42:33

标签: backbone.js coffeescript

代码:

  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

我可以通过调用asessions添加到a.save()后成功手动保存。

我想问题是Session构造函数触发了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语句?

1 个答案:

答案 0 :(得分:3)

我的建议是只调用save而不是set。所以取而代之:

a.set x: 'new'

a.save x: 'new'

希望对你有用