【问题标题】:Send action to all components from controller从控制器向所有组件发送操作
【发布时间】:2015-09-18 20:40:36
【问题描述】:

在我的 Ember 应用程序中,我有一个模型,它是一个从后端加载的数组。每个项目描述一个小部件。每个小部件类型都由 Ember 组件表示。用户在每个小部件中输入输入,现在需要立即评估所有小部件(按下按钮后,该按钮位于所有组件之外)。

如何做到这一点?我以为我可以使用 ember-component-inbound-actions 并向每个组件发送一个操作,但是我不知道如何将任意数量的小部件绑定到任意数量的控制器属性(字符串不起作用)。

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    您可以创建Ember.Service,它会发出事件,将其注入路由或控制器(用户单击按钮时发送动作的位置)和所有组件。然后,您应该在您的组件中订阅从Ember.Service 发出的事件,或者,如果它是共享逻辑,您可以使用特定方法创建Mixin 并在所有组件中使用它,并对控制器发出的那个动作做出反应。

    示例服务:

    export default Ember.Service.extend(Ember.Evented, {  
        emitButtonClicked() {
            this.trigger('buttonClicked');
        }
    });
    

    示例组件:

    export default Ember.Component.extend({
      theService: Ember.inject.service('theservice'),
    
      doSomethingWithInput() {
        this.set('randomProperty', true);
        console.log('Do something with input value: ' + this.get('inputVal'));
      },
    
      subscribeToService: Ember.on('init', function() {
        this.get('theService').on('buttonClicked', this,  this.doSomethingWithInput);
      }),
    
      unsubscribeToService: Ember.on('willDestroyElement', function () {
        this.get('theService').off('buttonClicked', this, this.doSomethingWithInput);
      })
    
    });
    

    示例控制器:

    export default Ember.Controller.extend({
      theService: Ember.inject.service('theservice'),
      actions: {
        buttonClicked() {
            this.get('theService').emitButtonClicked();
        }
      }
    });
    

    示例模板:

    <button {{action 'buttonClicked'}}>Global Button</button>
    
    First component:
    {{my-component}}
    
    Second component:
    {{my-component}}
    

    【讨论】:

    • 完美!非常感谢。有没有一种优雅的方式来从组件中收集数据?我知道我可以将一个动作从组件发送到控制器,但它似乎有点 hacky。
    • 将动作从组件发送到控制器是一种方法。 Ember 2.0 鼓励您大量使用操作 - “数据向下操作”。
    • 我发现了奇怪的行为 - 当我重新创建组件时(例如,通过转换到不同的路由并再次返回),不存在的组件仍在侦听服务(并且我得到“断言失败:在被破坏的对象上调用 set")。组件应该如何正确“取消订阅”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多