Ember mut helper — Let’s mutate!

Ed Huang
2 min readAug 17, 2016

--

mutant ninja tutles!

So if been using ember since 1.13 you’ve seen this mut for a while. I thought I’d do a deep dive and hopefully share some insights.

Here’s a link to the official Ember doc:
https://api.emberjs.com/ember/release/classes/Ember.Templates.helpers/methods/mut?anchor=mut

“The mut helper lets you clearly specify that a child Component can update the (mutable) value passed to it, which will change the value of the parent component.”

Mut by itself.

<!-- parent.hbs -->
{{clickable-ninja-turtle mutableTurtle=(mut turtle)}}
<!-- clickable-ninja-turtle.hbs -->

//clickable-ninja-turtle.hbs
<button>Transform!!!</button>

With that, inside my component I can do something like this:

//components/parent.js
export default Component.extend({
turtle: 'I\'m green!'
});

//components/clickable-ninja-turtle.js
export default Component.extend({
click: function() {
this.set('mutableTurtle', 'I\'m a ninja!');
}
});

Now inside turtle power, my turtle property should have the value of “I’m a ninja!”

Including the “action” helper

What seems to be more popular is using the mut helper in conjunction with an actions helper. This is a shortcut, and saves you from having to define an action if your main goal is just to update a property.

// Parent.hbs
<button onclick={{action (mut turtle) "I'm a ninja"}}>Transform!!!</button>

What’s happening is that the actions helper is turning our attribute into a function that takes in an implicit value and updates it with what’s passed in.

Our turtle has now become a ninja.

Conclusion

This is all to keep in line with Ember DDAU convention so that we don’t change things downstream, unless we are intentionally doing so.

Hope that helps. Would love to hear any feedback or insights. Go team ember!

Here’s a twiddle:
Ninja turtle twiddle

Update:

Thanks to thejsguy. The last section regarding “including the actions helper” the mut helper needs to be wrapped by an action helper for it to work. This essentially turns mutableTurtle into a function.

Here’s a twiddle of the example.

--

--

Ed Huang

Senior Frontend Developer at Auditboard.com, Love Ember.js and all things javascript.