获取后无法访问属性
我正在我的 Web 控制台中测试一些代码(使用 coffescript)
@user = new Onethingaday.Models.User()
@user.url= "/users/#{current_user.get('nickname')}.json?id_type=nickname"
@user.fetch()
console.log(@user)
console.log(@user.get("facebook_id"))
console.log(@user)
行显示以下内容:
但是,console.log(@user.get("facebook_id"))
显示未定义
。
我看到 user
具有 facebook_id
属性。我如何检索它的值?
I am testing some code in my web console (using coffescript)
@user = new Onethingaday.Models.User()
@user.url= "/users/#{current_user.get('nickname')}.json?id_type=nickname"
@user.fetch()
console.log(@user)
console.log(@user.get("facebook_id"))
The console.log(@user)
line shows the following:
However, console.log(@user.get("facebook_id"))
shows undefined
.
I see that user
has the facebook_id
attribute. How do I retrieve the value of it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这看起来像是一个时间问题,尽管很奇怪。
fetch
是异步的;在尝试访问任何属性之前,您需要等待其success
回调被调用。试试这个:
令人困惑的是,第一个
console.log
会显示user.attributes.facebook_id
存在,而第二个则不会,但console.log
> 在 Webkit 的实现中本身是异步的,所以发生的情况是@user.get
调用立即(同步)解析,而第一个console.log
中的对象检查代码> 正在解决稍后 -fetch
完成后。This looks like a timing issue, albeit an odd one.
fetch
is asynchronous; you need to wait until itssuccess
callback is called before trying to access any attributes.Try this:
It's confusing that the first
console.log
would showuser.attributes.facebook_id
existing and the second wouldn't, butconsole.log
is itself asynchronous in Webkit's implementation, so what's going on is that the@user.get
call is being resolved immediately (synchronously), whereas the object inspection in the firstconsole.log
is resolving later—after thefetch
completed.看起来facebook_id是@user对象的attributes属性的一个属性。如果是这样的话,我认为以下方法会起作用:
It looks like facebook_id is a property of the attributes property of the @user object. If that's the case, I'd think the following would work: