Backbone.js的:车型不显示 [英] Backbone.js: models not appearing

查看:74
本文介绍了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?

感谢。

推荐答案

调用是异步的:

The fetch call is asynchronous:

collection.fetch([选项])

取模型的默认设置为这个集合从服务器,当他们到达重新集合。选项​​散列接受成功错误会传递回调(收集,响应)作为参数。当模型数据从服务器返回时,集合将重置。

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 languages​​.models languages​​.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.

所以你的渲染应该看起来更像是这样的:

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.

这将更有意义叫 languages​​.fetch 初始化和绑定 @渲染来集合的重置事件;那么你可以把东西放在网页上,当收集已准备就绪。

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.

此外, _。bindAll @ 很少需要CoffeeScript的。你应该创建 =&GT的相关方法; 代替

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

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

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