2013-11-01 64 views
1

我有一个Document模型,它具有使用hasMany关系定义的属性/属性。目的是自由地定义文档的不同区域中的内容,如header,body,footer,同时还创建诸如colorimage之类的表示属性。Ember.js/Ember数据 - 渲染模板中有许多键/值对

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"}} 

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

回答

0

一种方法可以是增强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; 
} 

HB

<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> 
0

我不能让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}} 
+0

如果初始化代理阵列,如图我提供了答案,documentAttributes的环内,然后使用该阵列,以渲染你的模板,它应该工作正常。当然,当您存储attrs时,代理数组必须存储在您的控制器中。 – melc