Backbone.js: models not appearing

后端 未结 1 1694
执笔经年
执笔经年 2021-01-26 10:43

I want to display a simple list of languages.

class Language extends Backbone.Model

    defaults:
        id: 1
        language: \'N/A\'

class LanguageList ex         


        
1条回答
  •  北海茫月
    2021-01-26 11:05

    The fetch call is asynchronous:

    fetch collection.fetch([options])

    Fetch the default set of models for this collection from the server, resetting the collection when they arrive. The options hash takes success and error callbacks which will be passed (collection, response) as arguments. When the model data returns from the server, the collection will reset.

    The result is that your console.log languages.models is getting called before the languages.fetch() call has gotten anything back from the server.

    So your render should look more like this:

    render: ->
        languages.fetch
            success: -> console.log languages.models
        @ # Render should always return @
    

    That should get you something on the console.

    It would make more sense to call languages.fetch in initialize and bind @render to the collection's reset event; then you could put things on the page when the collection is ready.

    Also, _.bindAll @ is rarely needed with CoffeeScript. You should create the relevant methods with => instead.

    0 讨论(0)
提交回复
热议问题