Ember数据 - 在对象内分配值

时间:2013-04-06 23:14:10

标签: javascript ember.js handlebars.js

我开始使用ember并尝试从Api获取一些数据并将其分配给Emberjs模型。

我的api返回的内容如下:

    [
    {
        email: 'someemail@domain.com'
        name: {
            firstname: 'first name',
            lastname: 'last name'
        }
    }
    {
        email: 'someemail2@domain.com'
        name: {
            firstname: 'another first name',
            lastname: 'another last name'
        }
    },
    {
        email: 'someemail3@domain.com'
        name: undefined
    }

]

我的代码是:

App.Store = DS.Store.extend({
  revision: 12,
});

App.Store.registerAdapter('App.Users', DS.Adapter.extend({
  findAll: function(store, type, id) {
    $.getJSON('https://domain.com/users?callback=?', {
        'auth_token': token
    }).done(function(json){
        store.loadMany(type, json);
    });
  },
}));

App.Store.registerAdapter('App.Users', DS.Adapter.extend({
  findAll: function(store, type, id) {
    $.getJSON('https://domain.com/users?callback=?', {
        'auth_token': token
    }).done(function(json){
        store.loadMany(type, json);
    });
  },
}));

App.Router.map(function() {
    this.route("users", { path: "/users" });
});

App.UsersRoute = Ember.Route.extend({
  model: function() {
    return App.Users.find();
  }
});

App.Users = DS.Model.extend({
    email: DS.attr('string'),
    firstname: DS.attr('string'),
    didLoad: function() {
        console.log('model loaded', this.toJSON());
    }
});


 <script type="text/x-handlebars" data-template-name="users">
    {{#each model}}
        {{email}} - {{firstname}}
    {{/each}}
</script>

显然,对于数组中的每个对象,firstname都是空的。

有谁知道这样做的正确方法是什么?

由于

1 个答案:

答案 0 :(得分:1)

您是否尝试过像这样设置用户模型:

App.Adapter.map('App.User', {
  name: {embedded: 'always'}
});

App.User = DS.Model.extend({
  email: DS.attr('string'),
  name: DS.belongsTo('App.UserName')
});

App.UserName = DS.Model.extend({
  firstName: DS.attr('string'),
  lastName: DS.attr('string')
});