Javascript 使余烬在加载时解析hasMany关系

Javascript 使余烬在加载时解析hasMany关系,javascript,ember.js,ember-data,Javascript,Ember.js,Ember Data,我现在面临着一个大问题好几天了。我正在使用ember simple auth插件,它为我提供了一个可以通过代码或模板访问的会话对象。该会话对象存储帐户信息,如用户名、id和权限 我的模型是这样的: App.Right = DS.Model.extend({ label: DS.attr('string', { defaultValue: undefined }) }); App.Right.FIXTURES = [ { id: 1, label:

我现在面临着一个大问题好几天了。我正在使用ember simple auth插件,它为我提供了一个可以通过代码或模板访问的会话对象。该会话对象存储帐户信息,如用户名、id和权限

我的模型是这样的:

App.Right = DS.Model.extend({
    label: DS.attr('string', { defaultValue: undefined })
});

App.Right.FIXTURES = [
    {
        id: 1,
        label: 'Admin'
    }, {
        id: 2,
        label: 'Manager'
    }, {
        id: 3,
        label: 'User'
    }
];

App.User = DS.Model.extend({
    username: DS.attr('string'),
    rights: DS.hasMany('right', {async: true})
});

App.User.FIXTURES = [
    {
        id: 1,
        username: "Someone",
        rights: [1]
    }
];
然后,按照简单身份验证文档中的说明,我进行了以下设置:

App.initializer({
    name: 'authentication',
    initialize: function(container, application) {
        Ember.SimpleAuth.Session.reopen({
            account: function() {
                var userId = this.get('userId');
                if (!Ember.isEmpty(userId)) {
                    return container.lookup('store:main').find('user', userId);
                }
            }.property('userId')
        });
    ...
    }
});
在我的一个观点中,我正在这样做:

this.get('context.session.account.rights').toArray()
但它给了我一个空数组。这段代码在Ember.computed属性中执行


问题是如何在呈现视图之前解析account的子对象?

因为async:true this.get'context.session.account.rights'将返回承诺对象,所以您必须使用此.get'context.session.account.rights'。然后。。。看:

好吧,我终于让它开始工作了。它不能解决原来的问题,因为原来的问题是完全愚蠢的。使用async:true时,不可能同步解析关系。试图提前解决它并不是解决方案,因为您仍然不知道它何时实际解决

因此,解决方案如下:

$.each(this.get('cellContent.buttonList'), function(i, button) {
    button.set('hasAccess', false);
    this.get('context.session.account').then(function(res) {
        res.get('rights').then(function(result) {
            button.set('hasAccess', Utils.hasAccess(result.toArray(), button.rights));
        });
    });
});
使用以下cellContent.buttonList定义:

buttonList: [
    Ember.Object.create({
        route: 'order',
        label: 'Consult',
        rights: 'all'
    }), Ember.Object.create({
        route: 'order.edit',
        label: 'Edit',
        rights: [1, 2]
    })
]
解释 我们必须使用Ember.Object才能访问set方法。使用余烬对象非常方便。它允许我们在渲染过程后更改属性值,使视图根据刚才设置的新值进行更新。 因为它会更新视图,所以您不必再关心模型是否已解析


我希望这将帮助人们,就像帮助我一样。

不幸的是,这并不是那么简单。按照你的建议做会给我一个漂亮的:未捕获的TypeError:无法读取未定义的属性'then',看起来像,帐户本身还没有解决这是这个问题的重复:?不,不是。链接中的问题只是如何访问会话对象。现在的问题是数据是异步加载的,导致组件的呈现崩溃。@BavoVanGeit:你是对的,但它需要更多的反射。引发错误Uncaught TypeError:无法读取未定义的属性“then”,因为context.session.account还返回未解析的承诺。所以我不得不用嵌套的。