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.
相关文章