Backbone.js: models not appearing

2019-03-04 09:48发布

问题:

I want to display a simple list of languages.

class Language extends Backbone.Model

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

class LanguageList extends Backbone.Collection

    model: Language
    url: '/languages'

languages = new LanguageList

class LanguageListView extends Backbone.View

    el: $ '#here'

    initialize: ->
        _.bindAll @
        @render()

    render: ->
        languages.fetch()
        console.log languages.models

list_view = new LanguageListView

languages.models appears empty, although I checked that the request came in and languages were fetched. Am I missing something?

Thanks.

回答1:

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.