【发布时间】:2013-12-14 00:03:15
【问题描述】:
我正在使用 Backbone 编写一个小应用程序。我开始创建一个创建 SongsCollection 的 SongsView。我获取此集合以从我编写的外部 API 中检索数据。下一步是使用toJSON 方法渲染获取的数据,但是调用toJSON 会返回[undefined],尽管集合是Bakcbone.Collection 的一个实例。
这是我的代码(在咖啡脚本中):
应用:
songs = new SongsView
songs.render()
歌曲视图:
SongsCollection = require 'scripts/collections/songs'
class SongsView extends Backbone.View
el: '#songs'
render: ->
songs = new SongsCollection
songs.fetch
success: ( res ) =>
console.log (res instanceof Backbone.Collection) # true
console.log (res instanceof SongsCollection) # true
console.log (res.toJSON()) # [undefined]
歌曲集:
Song = require 'scripts/models/song'
class SongsCollection extends Backbone.Collection
model: Song
url: 'http://localhost:1337/songs'
歌曲:
class Song extends Backbone.Model
constructor: ({@name, @path}) ->
console.log 'new'
编辑:如果我查看原型链,我可以找到一个 toJSON() 方法:
EDIT²:单个模型的行为相同:
console.log (res.models[0].toJSON()) # undefined
这实际上很有趣。这意味着 SongsCollection 中的 toJSON 方法有效,但 Song 中的 toJSON 无效。我会在那里深入挖掘。
【问题讨论】:
-
您尝试调用
toJSON进行收藏,但您需要为收藏中的每个模型调用此函数 -
@jonijones 你确定吗? backbonejs.org/#Collection-toJSON
-
this.collection.each(function(){this.model.toJSON()}, this); -
在
render()函数中,您必须有权收集,在您的情况下为this.songs。试试console.log(this.songs.toJSON);。但是对于渲染,你需要渲染集合的每个模型。 -
嗯。其实我觉得你错了。如上面链接中所述,您可以在集合上调用
toJSON。它返回每个模型的toJSON方法的结果。我找到了我的问题的解决方案,我使用的是构造函数而不是初始化,它绕过了 Backbone.Model 魔法。
标签: javascript backbone.js coffeescript backbone.js-collections