从模型的类名到它的类型

时间:2014-02-09 00:45:23

标签: ember.js ember-data

我正在使用Ember Data,可以轻松地动态查找模型的类名。例如,如果我有一个名为Foobar的模型和一个名为FoobarsController的控制器,它是一个数组控制器,其content属性指向模型,那么我可以:

FoobarsController = Ember.ArrayController.extend({
    foobarClassName: function() {
        return this.get('content.typeKey');
    }.property()
}

这将导致foobarClassName等于“App.Foobar”。大。现在,如果我想将其解析回模型的类型,在这种情况下foobar

1 个答案:

答案 0 :(得分:0)

我仍然不知道如何使用Ember API调用这样做,所以我只创建了自己的 mixin ,它为控制器底层模型提供了一些元属性,包括我自己的狡猾计算模型的“类型”(也就是说,所以你可以动态地使用它来调用find(type)方法)。

以下是代码:

App.ModelMetaMixin = Ember.Mixin.create({
    _modelProperty: 'content', // the property on the controller to find the bound reference to the model (typically found at 'content')
    modelRef: function() {
        var property = this._modelProperty;
        return this.get(property + '.constructor');
    }.property(this._modelProperty),
    modelName: function() {
        return String(this.get('modelRef'));
    }.property(this._modelProperty),
    modelType: function() {
        var name = this.get('modelName').split('.');
        return Ember.String.camelize(name.pop());
    }.property(this._modelProperty)
}

有关此问题的解决方案,请参阅modelType实施。希望这可以帮助。如果我在接下来的几天内没有得到更好的答案,我会接受我自己的答案。

相关问题