Ember.js - 无法访问已加载的记录

时间:2014-03-13 17:35:34

标签: javascript ember.js

我想在加载用户后更改RESTAdapter的标题,但无法访问属性。

任何想法为什么?

相关守则:

var user = '';
App.MainRoute = Ember.Route.extend({
model: function(params){
    user = this.store.find('user',{email: params.email});
    alert(user.hash); //get a undefined
    return user;
},
actions:{
    addList: function(){
        var list = this.store.createRecord('list', {
            name: 'New list',
            desc: 'Describe it here'
        });
        this.store.find('user', 1).then(function(user){
            list.set('user', user);
        })
        list.save();
    }
}
})

this.store.find('user', {email: params.email});上的Json回复:

{
  "users": [
    {
      "id": 1,
      "hash": "66ff7d6eae591ca2a7d6b419991690e8",
      "email": "marvin@blabla.de",
      "name": "",
      "lists": []
    }
  ]
}

模型定义:https://gist.github.com/Osile/5544ccab1997c4da2b5b

1 个答案:

答案 0 :(得分:1)

您必须在模型中返回Promise,但您也可以提前访问它。代码:

model: function(params){
    users = this.store.find('user', { email: params.email }); // returns promise
    users.then(function(item) { // resolves promise
        user = item.get('firstObject');
        alert(user.get('hash'));
    });
    return users; // model will wait for data
}

有效。您可以使用以下Handlebars.js模板:

<script type="text/x-handlebars" data-template-name="main">
    From model:
    <ul>
    {{#each}} <!-- Iterate over array resolved from promise. -->
        <li>{{hash}}</li>
    {{/each}}
    </ul>
</script>

完整代码:emberjs.jsbin.com