Backbone.js:模型没有出现 [英] Backbone.js: models not appearing

查看:15
本文介绍了Backbone.js:模型没有出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示一个简单的语言列表.

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 显示为空,尽管我检查了请求是否已进入并已获取语言.我错过了什么吗?

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

谢谢.

推荐答案

fetch 调用是异步的:

The fetch call is asynchronous:

fetch collection.fetch([options])

从服务器获取此集合的默认模型集,当它们到达时重置集合.选项哈希采用 successerror 回调,它们将作为参数传递 (collection, response).当模型数据从服务器返回时,集合将重置.

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.

结果是您的 console.log 语言.modelslanguages.fetch() 调用从服务器返回任何内容之前被调用.

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

所以你的 render 应该看起来更像这样:

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.

initialize 中调用 languages.fetch 并将 @render 绑定到集合的 reset 事件;然后你可以在集合准备好时把东西放在页面上.

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.

此外,CoffeeScript 很少需要 _.bindAll @.您应该使用 => 创建相关方法.

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

这篇关于Backbone.js:模型没有出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆