Backbone.js: models not appearing

 ̄綄美尐妖づ 提交于 2019-12-20 06:09:29

问题


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.



来源:https://stackoverflow.com/questions/9245830/backbone-js-models-not-appearing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!