Backbone.js: models not appearing(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])
从服务器获取此集合的默认模型集,当它们到达时重置集合.选项哈希采用 success
和 error
回调,它们将作为参数传递 (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 语言.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.
所以你的 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:模型没有出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Backbone.js:模型没有出现
基础教程推荐
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01