在Ember.js中查找组件并更改其属性

时间:2014-02-26 08:19:35

标签: ember.js ember-controllers

我有一个模板,可以为模型中的每条记录创建一个组件。我想找到一个组件,并根据其他模板中的事件在运行时更新其中一个属性。如何查找插入DOM中的特定组件。          {{#每}}     {{我的名字}}     {{/每}}     

<script type="text/x-handlebars" data-template-name="components/my-name">
Hi, my name is {{name}}.
</script>

var App = Ember.Application.create();
App.IndexRoute=Ember.Route.extend({
model:function(){
 return dummyNames;
} 
});
var dummyName={[name='John', name='Jane', name='Jade']};

此代码将在屏幕上显示名称。现在我有另一个名为change的模板。

<script type="text/x-handlebars" data-template-name="change">
<button {{action 'changeNow'}}></button>
</script>

App.ChangeController=Ember.Controller.extend({
    actions:{
        changeNow:function(){
           //Here I want to find the component where the name is Jane and change it to Kate. How         to do this?
        }
    }
});

1 个答案:

答案 0 :(得分:0)

这是我为你准备的一个jsbin。

http://emberjs.jsbin.com/sanukoro/3/edit

组件有自己的范围。如果{{name}}显示在您认为已在索引模板中呈现的组件中。这意味着您已将该属性传递给组件。 来自指南

的类似内容
{{blog-post title=name}}

passing properties to components

所以basicall你要修改的属性是IndexController。

您可以直接修改IndexController属性(dummynames),由于数据绑定,更改将反映在您的组件中。

由于你想在不同的控制器中一起完成它,你必须在ChangeController中声明对IndexController的依赖。 Managing dependencies

App.ChangeController=Ember.Controller.extend({
    needs: ['index'] //dependency
    names: Ember.computed.alias("controllers.content") //now get properties of Index controller
    actions:{
        changeNow:function(){
          //here you can find name jane and replace it with to kate

        }
    }
});

您可能需要查看addArrayObserver以密切跟踪更改。

相关问题