Ember.js {{render}}辅助模型未正确设置

时间:2013-11-26 13:01:28

标签: javascript ember.js ember-data

我遇到了一个奇怪的问题。我有一个文章模板。在文章模板中,我调用{{render "category/new" category}}

但是,在通过操作保存新类别时,会使用错误的模型。当我将其更改为{{render "category/new" this}}时,它会使用文章模型。当我将模型部件留空时,它也不起作用。

模板

<script type="text/x-handlebars" data-template-name="article">
    ((...))
    {{render "category/new" category}} // calls the popup for adding a new category
    ((...))
</script>

<!-- popups -->
<script type="text/x-handlebars" data-template-name="category/new">
    <div class="popup">
        <h2>Add new category</h2>

        Name: {{input type="text" value=name}}<br />
        Image: {{view App.UploadFile name="image" file=image }}<img {{bind-attr src=image}}><br />
        Category-parent: {{input value=categoryRelation}}<br />

        <button {{action 'saveCategory'}}>Save</button>
        </div>
</script>

路由器

// both routes have the render called, it uses the same template
this.resource('article', {path: '/article/:id'}); 
this.resource('article.new', {path: "/article/new"});

模型

App.Category = DS.Model.extend({
    name: DS.attr('string'),
    image: DS.attr('string'),
    categoryRelation: DS.belongsTo('category')
});

App.Article = DS.Model.extend({
    name: DS.attr('string'),
    category: DS.hasMany('category')
)};

控制器

App.CategoryNewController = Ember.ObjectController.extend({
    actions: {
        saveCategory: function () {
            console.log('CategoryNewController saveCategory action'); // gets called
            console.log(this.get('model')); // the wrong one
            this.get('model').save(); // saves all categories when using {{render "category/new" category}} 
        }
    }
});

请注意,Category / new没有路由,因为{{render}}帮助器不需要它。请参阅:http://emberjs.com/guides/templates/rendering-with-helpers/#toc_specific(参见页面底部的表格)

1 个答案:

答案 0 :(得分:2)

在文章中,categoryhas-many,因此您要将CategoryNewController的模型设置为Category的数组(除非您遗漏了一部分,当用户点击new或其他内容时,会创建一个Category对象。)