Backbone.js:模型未出现
我想显示一个简单的语言列表。
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
显示为空。我错过了什么吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fetch
调用是异步的:结果是,在
languages.fetch()
调用从服务器返回任何内容之前,您的console.log languages.models
就被调用了。所以你的渲染应该看起来更像这样:
这应该会让你在控制台上看到一些东西。
在
initialize
中调用languages.fetch
并将@render
绑定到集合的reset
事件会更有意义;然后当集合准备好时,您可以将内容放在页面上。此外,CoffeeScript 很少需要
_.bindAll @
。您应该使用=>
创建相关方法。The
fetch
call is asynchronous:The result is that your
console.log languages.models
is getting called before thelanguages.fetch()
call has gotten anything back from the server.So your
render
should look more like this:That should get you something on the console.
It would make more sense to call
languages.fetch
ininitialize
and bind@render
to the collection'sreset
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.