【问题标题】:How do I resolve a model class from a String name in Ember data?如何从 Ember 数据中的字符串名称解析模型类?
【发布时间】:2013-04-11 15:36:33
【问题描述】:

我正在尝试使用 ember-data,我需要能够动态解析给定字符串的模型名称。

我查看了 ember-data 代码库,但在那里找不到任何东西。然后我在 ember 中找到了这个:

/**
  @private

  This function defines the default lookup rules for container lookups:

  * templates are looked up on `Ember.TEMPLATES`
  * other names are looked up on the application after classifying the name.
    For example, `controller:post` looks up `App.PostController` by default.
  * if the default lookup fails, look for registered classes on the container

  This allows the application to register default injections in the container
  that could be overridden by the normal naming convention.

  @param {Ember.Namespace} namespace the namespace to look for classes
  @return {any} the resolved value for a given lookup
*/
function resolverFor(namespace) {

  resolve: function(fullName) {
    return this.resolver(fullName) || this.registry.get(fullName);
  },

  normalize: function(fullName) {
    return fullName;
  },

  lookup: function(fullName, options) {

我会假设 ember-data 与此功能挂钩,所以我可以这样做:

App.resolver.resolveModel "model:#{modelName}"

但是,唉,不……

也许这是要走的路? (来自 store.js 行 ~1500)

  typeMapFor: function(type) {
    var typeMaps = get(this, 'typeMaps');
    var guidForType = Ember.guidFor(type);

    var typeMap = typeMaps[guidForType];

    if (typeMap) {
      return typeMap;
    } else {
      return (typeMaps[guidForType] =
        {
          idToCid: {},
          clientIds: [],
          recordArrays: []
      });
    }
  },

看起来商店内部有某种类型映射?

【问题讨论】:

    标签: model ember.js ember-data


    【解决方案1】:

    如果您声明了模型,序列化程序就知道如何执行此操作。见DS.Serializer typeFromAlias

    https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/serializer.js#L1103

    你的字符串是从哪里来的?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多