Ember.js{{render}}助手模型设置不正确

Ember.js {{render}} helper model not correctly set

本文关键字:模型 设置 不正确 render Ember js      更新时间:2023-11-09

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

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

模板

<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(参见页面底部的表格)

在文章中,categoryhas-many,因此您将CategoryNewController的模型设置为Category的数组(除非您在用户单击新的或其他东西时遗漏了创建Category对象的部分)