1

我正在尝试向 ember 组件添加一些外部功能。该组件如下:

应用程序/模板/programmers.hbs

{{echo-hlabel-tf 
   id= "id-test-hlabel"
   class="class-test-hlabel-mio"
   label="Horizontal textfield"
   textValue="..."
   regExp="^([a-z0-9]{5})$"
   errorMsg="Text hasn't five characters"
   fnActionButtonClicked = "sayHello"
}}

我正在使用参数'fnActionButtonClicked'。此参数表示它执行的函数,它不在组件的功能范围内(例如将 javascript 函数作为参数传递)。我是新手,我不知道确切的 ember 方法。组件的模板是:

应用程序/模板/组件/echo-hlabel-tf.hbs

<div id="echo-hlabel-tf">
    <span id="{{id}}-echo-hlabel-tf-label" 
          class="{{class}}-echo-hlabel-tf-hlabel">
    {{label}}
</span>
<span id="{{id}}-echo-hlabel-tf-value" 
      class="{{class}}-echo-hlabel-tf-value">
    {{input id='input-id' class='input-class' value=textValue
            focus-out = (action 'validateRegExp' textValue regExp) 
    }}
</span>
<span id="{{id}}-echo-hlabel-tf-error-msg" 
 class="{{class}}-echo-hlabel-tf-error-msg">
    <p id='error-msg' class="error-msg">
        {{errorMsg}}
    </p>
</span>

<div>
    <h2>Testing passing functions to the component</h2>
        <input type="button" {{action "actionButtonClicked"}}/>
</div>
</div>

如您所见,在模板的底部,有一个 input type="button" 与 "actionButtonClicked" 绑定。组件的控制器是:

应用程序/组件/echo-hlabel-tf.js

import Ember from 'ember';

export default Ember.Component.extend({
   classNameBindings:['error'],
   error:false,

   actions: {
    validateRegExp(text,regExpStr,event){
        let regExpObj = new RegExp(regExpStr)
        if(regExpObj.test(text)){
            this.set('error',false);
        }else{
            this.set('error',true);
        }
    },
    actionButtonClicked(){
        console.log('Arrives to the component');
        var action = this.get('fnActionButtonClicked');
        console.log(action);
        // How can I call the function in another controller
        // With parameter fnActionButtonClicked name
    }
 }
});

因此,模板“fnActionButtonClicked”(SayHello)的参数将通过var action = this.get('fnActionButtonClicked');在actionButtonClicked()中检索到。.

所以,在这一点上,疑问来了。由于我不能将 javascript 函数作为模板的参数传递(或者至少,我认为这不是正确的做法),我创建了一个控制器“sampleController”来创建操作“sayHello”(参见参数fnActionButtonClicked 值),代码如下:

应用程序/控制器/sample-controller.js

从“ember”导入 Ember;

export default Ember.Controller.extend({
   actions:{
    sayHello(){
        console.log("I'm saying hello this time");
    }
  }

});

我怎样才能从app/components/echo-hlabel-tf.js:actionButtonClicked()执行app/controllers/sample-controller.js 的代码:sayHello()?如何从组件控制器访问另一个控制器?这是实现我目标的正确方法吗?

提前致谢

4

1 回答 1

1

您需要为特定路由创建控制器,而不是 sample-controller.js programmers。所以创建app / controllers / programmers.js文件,

export default Ember.Controller.extend({
  actions:{
    sayHello(){
      console.log("I'm saying hello this time");
    }
  }
})

和内部组件app / components / echo-hlabel-tf.js

actionButtonClicked(){
  console.log('Arrives to the component');
  this.sendAction('fnActionButtonClicked');        
}
于 2017-05-24T13:25:54.437 回答