Paul Cowan

Nomadic cattle rustler and inventor of the electric lasso

Emberjs - Passing Block Params From a Component

I have previously blogged about a hack I had to use to get the right context when using a component in its block form.

The example I gave in the post was for an autocomplete component that would give the developer the ability to prepend their own customisation to a selection. The example I gave was prepending an avatar like in the image below.

The original component could be used in its block form like this:

And here is the original component template file:

There is no way in the above to set what the context would be for the code block that is ran when the yield helper is called. The context was non-negotionable and the context would be that of the template it was declared in e.g. the controller. The only way round this was the hack that I described in the previous post.

As of ember 1.10.0, it is possible to pass internal values to a down stream scope with the new block params syntax.

I can refactor my component’s template to look like this:

  • Line 1 uses the each helper with the new block params syntax to specify a context named selection.
  • Line 4 uses the yield helper to pass the block param to the template or code block that is rendered between the component’s definition.

Below is how I can use the block param when the component is declared with a block:

  • line 2 binds the selection var that is passed to this code block via the yield helper in the previous code example.
  • line 3 puts the var to use.

Here is a jsbin with a working simpler example.