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'
편집 : 하나의 모델 같은 동작 :
EDIT² :
console.log (res.models[0].toJSON()) # undefined
이다 나는 프로토 타입 체인을 보면, 나는 toJSON()하지만 방법을 찾을 수 있습니다 실제로 흥미 롭습니다. 즉, SongsCollection의 toJSON
메서드는 작동하지만 toJSON
은 Song
입니다. 나는 거기에서 더 깊게 파다.
당신은 수집을 위해''toJSON''를 호출하려고하지만 당신은 컬렉션의 각 모델 –
@jonijones 당신이 확신이 함수를 호출해야합니까? http://backbonejs.org/#Collection-toJSON – Simon
''this.collection.each (function() {this.model.toJSON()}, this);'' –