Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Collection没有方法toJSON_Javascript_Backbone.js_Coffeescript_Backbone.js Collections - Fatal编程技术网

Javascript Collection没有方法toJSON

Javascript Collection没有方法toJSON,javascript,backbone.js,coffeescript,backbone.js-collections,Javascript,Backbone.js,Coffeescript,Backbone.js Collections,我正在用主干网编写一个小应用程序。我开始创建一个SongsView,它创建了一个SongsCollection。我获取此集合以从我编写的外部API检索数据。下一步是使用toJSON方法呈现获取的数据,但是调用toJSON返回[undefined],尽管集合是Bakcbone.collection的实例 以下是我的代码(在coffeescript中): 应用程序: SongsView: SongsCollection = require 'scripts/collections/songs' c

我正在用主干网编写一个小应用程序。我开始创建一个SongsView,它创建了一个SongsCollection。我获取此集合以从我编写的外部API检索数据。下一步是使用
toJSON
方法呈现获取的数据,但是调用
toJSON
返回
[undefined]
,尽管集合是Bakcbone.collection的实例

以下是我的代码(在coffeescript中):

应用程序:

SongsView:

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()方法:

编辑²:单个模型的相同行为:

console.log (res.models[0].toJSON()) # undefined

这其实很有趣。这意味着来自歌曲集合的
toJSON
方法可以工作,但是来自
Song
toJSON
方法不能工作。我会在那里挖得更深。

问题解决了。我使用的是
构造函数
而不是
初始化
,这导致创建一个没有任何
属性的模型
,因此,调用toJSON返回
未定义
,因为
属性未定义

class Song extends Backbone.Model

initialize: ({@name, @path}) ->
    console.log 'new'

您尝试调用
toJSON
进行集合,但需要为集合中的每个模型调用此函数collection@jonijones你确定吗<代码>this.collection.each(函数(){this.model.toJSON()},this)
render()
函数中,在您的情况下,
this.songs
必须具有收藏权限。尝试
console.log(this.songs.toJSON)。但对于渲染,需要渲染collection.Mmh的每个模型。事实上,我认为你错了。如上面链接中所述,您可以对集合调用
toJSON
。它返回每个模型的
toJSON
方法的结果。我找到了问题的解决方案,我使用构造函数而不是绕过主干的初始化。
class Song extends Backbone.Model

initialize: ({@name, @path}) ->
    console.log 'new'