PCR
PCR

Reputation: 275

ember - closure action results in error, will not render page unless action is provided in component

I'm trying to understand closure actions and am just testing out some code, however I can't seem to get it to work. In my index.hbs template I have rendered a component like so:

{{test-component test=(action 'foo')}}

In my index.js controller I have defined the action foo:

  foo: function () {
    console.log('foo executed');
  },

And in my test-component.hbs component I have a button that triggers the action like so:

<button {{action (action 'test')}}>Test Button</button>.

However the page crashes and I get the following error in the console: Uncaught Error: An action named 'test' was not found

I can make the page render again by inserting a test action in the test-component.hbs however I was under the impression that you using closure actions, you didn't need to put anything in your component? What am I doing wrong here?

Upvotes: 2

Views: 244

Answers (1)

nem035
nem035

Reputation: 35491

The simple way you can think about closure actions is just passing function references.

In your given code, when you say

{{test-component test=(action 'foo')}}

You are basically saying

Grab the action 'foo' from the current context and pass it as the property test

which in pseudo-code for your specific example could look like:

{{test-component test=IndexController.actions.foo}}

That means property test within test-component points to the same function that is the action foo in the index controller.

Thus, you would just use it directly:

// test is an action passed into test-component
<button {{action test}}>Test Button</button>.

Here's a simple EmberTwiddle example.

When you say {{action (action 'test')}} within your test-component, its looking for the action test within its current context, which is the component itself and the component doesn't have an action test, it has a property called test which happens to point to an action from its outer context, the index controller.

Upvotes: 3

Related Questions