Ember.js / Ember Data - 渲染模板中有许多键/值对



我有一个Document模型,它使用hasMany关系定义了属性/属性。目的是能够自由地定义文档不同区域的内容,如headerbody footer,同时还创建表示属性,如colorimage

KF.Document = DS.Model.extend
  title: DS.attr 'string'
  documentAttributes: DS.hasMany 'documentAttribute'
KF.DocumentAttribute = DS.Model.extend
  attrKey: DS.attr 'string'
  attrValue: DS.attr 'string'
  document: DS.belongsTo 'document'

Document.documentAttributes返回一个DS.ManyArray因此为了呈现它,我可以执行以下操作:

{{#each da in documentAttributes}}
  <p>{{da.attrKey}} - {{da.attrValue}}</p> <!-- returns: "header - this is my header" -->
{{/each}}

问题是我想直接访问密钥(使用代理?),所以我可以直接绑定数据,如下所示:

{{textarea value=documentAttributes.header cols="80" rows="6"}}
<img {{ bindAttr src="documentAttributes.imageSrc" }} >
{{textarea value=documentAttributes.footer cols="80" rows="6"}}

我应该如何处理这个问题?

一种方法可能是增强 em 视图(对于勇敢的人来说也可能是一个组件),或者创建一个代理,该代理接收 DocumentAttribute 对象并动态定义一个属性,该属性名为 attrKey 的值并返回 attrValue 的值。您可以使用以下代码实现此目的,

http://emberjs.jsbin.com/ehoxUVi/2/edit

.js

App = Ember.Application.create();
App.Router.map(function() {
});
App.IndexRoute = Ember.Route.extend({
  model: function() {
    return createProxy(App.DocumentAttribute.create());
  }
});
App.DocumentAttribute = Ember.Object.extend({
  attrKey:"theKey",
  attrValue:"theValue"
});

 function createProxy(documentAttr){
  App.DocumentAttributeProxy = Ember.ObjectProxy.extend({
    createProp: function() {
      _this = this;
      var propName = this.get('attrKey');
      if (!_this.get(propName)) {
        return Ember.defineProperty(_this, propName, Ember.computed(function() {
          return _this.get('attrValue');
        }).property('attrKey'));
      }
    }.observes('content')
  });
  var proxy = App.DocumentAttributeProxy.create();
  proxy.set('content',documentAttr);
  return proxy;
}

乙肝

<script type="text/x-handlebars">
    <h2>Welcome to Ember.js</h2>
    {{outlet}}
  </script>
<script type="text/x-handlebars" data-template-name="index">
    {{attrKey}}
    <br/>
    {{attrValue}}
    <br/>
    {{theKey}}
  </script>

我无法让 melc 的解决方案与 DS 配合使用。ManyArray 由关系返回。

但是他的例子给了我一些想法,我做了以下工作。基本上通过控制器上的"快捷键"映射项目。

KF.DocumentsShowRoute = Ember.Route.extend
  setupController: (controller, model) ->
    controller.set('model', model)
    # make an `Object` to store all the keys to avoid conflicts
    controller.set('attrs', Ember.Object.create())
    # loop through all `DocumentAttributes` in the `DS.ManyArray` returned by the relationship,
    # get the `attrKey` from each item and make a shortcut to the item under `attrs` object
    model.get('documentAttributes').forEach (item, index, enumerable) -> 
      key = item.get('attrKey')
      controller.get('attrs').set(key, item)

模板,其中标头attrKey

{{input value=attrs.header.attrValue}}

最新更新