简体   繁体   中英

Is it possible to pass a function to an Ember.js component to execute it as an action callback?

I'm wondering if it's possible to pass a function as a parameter of an Ember component

// component.hbs
{{component fun=fun}}

and then, from an action in the component, calling this same function :

// component.js
actions: {
  fun2() {
     let fun = this.get('fun');
     fun();
  }
}

Check out the following twiddle . What you are asking is valid and works. But in general you can pass a function to a component with an action helper and define your action within actions definition. What I can say is this is the common way of passing a function to a component and triggering an action (calling the function) from within the component.

my-component.js

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    buttonClicked() {
      let foo = this.get('foo');
      foo();
    }
  }
});

application.js

import Ember from 'ember';

export default Ember.Controller.extend({
  appName: 'Ember Twiddle',

  foo() {
    alert('hi there');
  }
});

application.hbs

<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
{{my-component foo=foo}}
<br>
<br>

my-component.hbs

<button onclick={{action 'buttonClicked'}}>Press</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM