Ember.js将动作发送到'belongsTo'相关模型的控制器

时间:2014-10-14 22:13:57

标签: javascript ember.js

我有一个孩子"像这样的模板,使用" child"的数组进行渲染。记录:

{{#each}}
    {{render "parent.edit" parent}}
{{/each}}
<button {{action="submit"}}>Submit</button>

&#34; parent.edit&#34;像这样的模板:

{{input type="text" value=parentProp}}

基本上我想要发生的是,当点击提交按钮时,每个&#34;孩子&#34;通过向ParentEditController发送动作来告诉其父模型保存自己,ParentEditController根据控制器状态执行一些操作,然后触发模型保存(其属性绑定到文本输入)。

对于我拥有的控制器和型号:

App.Child = DS.model.extend({
    parent: DS.belongsTo('parent', {async: true})
});

App.Parent = DS.model.extend({
    parentProp: DS.attr('string')
});

App.ChildrenController = Ember.ArrayController.extend({
    itemController: 'child',
    actions: {
        submit: function() {
            //How can I send 'save' to each child.parent?
            this.forEach(function(item) {
                item.send('saveParent'); //Calls ChildController, which has a model
            });
        }
    }
});

App.ChildItemController = Ember.ObjectController.extend({
    needs: ['parentEdit'],
    actions: {
        saveParent: function() {
            //Here is the problem.  How do I get a non-singleton instance (has a model) of ParentItemController?
            this.get('controllers.parentEdit').send('doStuffThenSave'); //This sends to a singleton instance of the controller without a model.
            this.get('parent').send('doStuffThenSave'); //This sends to the model directly and does not hit any controller
        }
    }
});

App.ParentEditController = Ember.ObejctController.extend({
    actions: {
        doStuffThenSave: function() {
            //Here there is some code to do some stuff that is dependent on other controller properties before I save the model.
            this.get('model').save(); //should update 'parentProp' based on the input
        }
    }
});

在代码注释中,问题是如果我尝试使用&#39; needs&#39;引用ParentEditController,那么我得到一个单例实例,因为控制器是在行{{1 }}。即,我理解它的方式,&#39;需要&#39;只有在路径中设置控制器或某个地方的父模板中时,才会为您提供带模型的控制器。如果我直接进入模型,那么我无法访问控制器。我怎么能同时拥有这两个?

1 个答案:

答案 0 :(得分:0)

在App.ChildItemController中你应该改变

this.get('controllers.parentEdit').send('doStuffThenSave'); 
this.get('parent').send('doStuffThenSave');

this.get('controllers.parentEdit').send('doStuffThenSave', this.get('model').get('parent'));

doStuffThenSave: function() {...}

doStuffThenSave: function(<param-name>) {...}

因为您没有向ParentEditController发送任何上下文并且没有定义模型,所以它使用的是没有信息的代理模型。通过发送上下文并定义一个参数,您将发送上下文(在本例中为子项的父模型),以供parentEdit.doStuffThenSave使用。

请参阅 Ember.Controller.send

您还需要更改

this.get('model').save();

<param-name>.save();

侧点,不要忘记在保存后用then()处理错误/成功!

Guide on emberjs.com

相关问题