【问题标题】:Finding a component and changing its property in Ember.js在 Ember.js 中查找组件并更改其属性
【发布时间】:2014-02-26 08:19:34
【问题描述】:

我有一个模板,它为模型中的每条记录创建一个组件。我想找到一个组件并在运行时根据来自其他模板的事件更新它的一个属性。如何找到插入到 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?
        }
    }
});

【问题讨论】:

  • 你在哪里展示你的组件?哪个模板? {{我的名字}}

标签: ember.js ember-controllers


【解决方案1】:

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

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

组件有自己的作用域。如果 {{name}} 显示在您的组件中,我假设您已在索引模板中呈现。这意味着您已将该属性传递给组件。 指南中的类似内容

{{blog-post title=name}}

passing properties to components

所以基本上你要修改的属性都是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 以密切跟踪更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2018-10-06
    • 1970-01-01
    相关资源
    最近更新 更多