0

Backbone을 사용하는 작은 앱을 쓰고 있습니다. SongsCollection을 만드는 SongsView를 만들기 시작합니다. 내가 작성한 외부 API에서 데이터를 검색하기 위해이 콜렉션을 가져온다. 다음 단계는 toJSON 메서드를 사용하여 가져온 데이터를 렌더링하는 것이지만 toJSON을 호출하면 컬렉션이 Bakcbone.Collection의 인스턴스 임에도 불구하고 [undefined]을 반환합니다.Backbone.Collection에는 메소드가 없습니다 .JSON

앱 :

songs = new SongsView 
songs.render() 

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] 

SongsCollection :

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' 

편집 : 하나의 모델 같은 동작 : enter image description here

EDIT² :

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

이다 나는 프로토 타입 체인을 보면, 나는 toJSON()하지만 방법을 찾을 수 있습니다 실제로 흥미 롭습니다. 즉, SongsCollection의 toJSON 메서드는 작동하지만 toJSONSong입니다. 나는 거기에서 더 깊게 파다.

+0

당신은 수집을 위해''toJSON''를 호출하려고하지만 당신은 컬렉션의 각 모델 –

+0

@jonijones 당신이 확신이 함수를 호출해야합니까? http://backbonejs.org/#Collection-toJSON – Simon

+0

''this.collection.each (function() {this.model.toJSON()}, this);'' –

답변

1

문제가 해결되었습니다. 내가 attributes없이 모델을 생성하는 initialize 대신 constructor을 사용 했으므로 toSSON을 호출하면 attributes 속성이 정의되지 않았기 때문에 undefined을 반환했습니다.

class Song extends Backbone.Model 

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