1

I'm using coffeescript. My code is pretty simple:

class SomeCollection extends Backbone.Collection
  constructor: (@options) ->
  url: ->
    "#{$SCRIPT_ROOT}/some/data/#{@options.someId}"
  model: SomeModel

class SomeView extends Backbone.View
  initialize: ->
    myCollection = new SomeCollection()
    myCollection.fetch
      success: (coll, resp) ->
        console.log coll

The JSON that's being returned from my collection's url is exactly:

[{"id": 1, "comments": "", "name": "images/exceptions/59.png"}]

However, before anything is printed to the console, I receive a backbone.js error on line 768: Cannot read property 1 of undefined. The undefined object is this._byId within the collection's get function. How can I solve this problem?

4

1 回答 1

5

您正在扩展Backbone.Collection并提供自己的构造函数,因此您需要确保调用父构造函数。

constructor: (@options) ->
  super null, @options

此外,集合的标准参数是(models, options),所以我会坚持下去。

constructor: (models, @options) ->
  super models, @options

或者更好的是,使用initialize而不是constructor完全避免这种情况

initialize: (models, @options) ->
于 2013-08-27T05:20:57.893 回答