create
Backbone.LocalStorage 在调用集合时会在客户端存储玩家列表players
,但稍后不会获取存储的模型,即使我可以在 localStorage 中检查它们。我可以调用@collections.players.localStorage.findAll()
来检索所有存储的对象并手动将它们推送到我的集合中。
class App.Models.Player extends Backbone.Model
defaults:
name: 'Unnamed'
team: 'Unassigned'
class App.Collections.Players extends Backbone.Collection
localStorage: new Backbone.LocalStorage('players')
model: App.Models.Player
class App.ViewModels.Game extends kb.ViewModel
constructor: ->
@collections =
players: new App.Collections.Players()
@collections.players.fetch(
success: (collection) =>
console.log(collection) # shows none
console.log(@collections.players.localStorage.findAll())
# shows all the stored players
)
# @players below is rendered by a foreach in a knockout template
@players = kb.collectionObservable @collections.players, { view_model: App.ViewModels.Player }
addPlayer: -> # called when a button is pressed
@collections.players.create(new App.Models.Player({ name: 'New Player' }))
return
为什么 Knockback 无法自动获取存储的实体?
以下调用手动检索所有对象:
_.each @collections.players.localStorage.findAll(), (elem) =>
@collections.players.add(elem)