partial application in ember templates 2020-07-16

I'll spend a few moments showing an example of partial application in Ember templates.

I've heard the term partial application before. Yet the meaning escapes me. So I'll demystify some Ember magic to demonstrate how it works. I presume you are somewhat familiar with Ember applications and are familiar with JavaScript. I use the terms method and function loosely too. If you are not, don't worry. You can explore the guides to become familiar. Or just read along!

partial application

Partial application means you use some of a function's arguments. Let's explore this in an Ember application.

Note: I have uploaded the first step to a public repository

I created a component called boredom. Its template contains:

<button onclick={{fn this.yawn 'zzz'}}>Yawn</button>

And its backing class:

import Component from '@glimmer/component';
import { action } from '@ember/object';

export default class BoredomComponent extends Component {
  @action
  yawn(message) {
    window.alert(message);
  }
}

Click the button and you should see zzz in an alert modal. We have witnessed partial application at work! Wait, how so? When we call the window.alert method, We are only using some of the arguments passed to the yawn method. Consider an updated version of the yawn method:

  yawn(message, event) {
    window.alert(`${message} ${event.type}`);
  }

I added the event parameter to the yawn method and then used it. Now when you click the button you should see the alert message zzz click.

Note: You can find the result of these changes in the step2 branch.

conclusion

Ember templates use modern JavaScript techniques for flexible functions. JavaScript functions are palm trees. Techniques like partial application bend them to our software whims.

references

  • Stefanov's "JavaScript Patterns" book has an excellent summary of partial application and currying. I've often seen both discussed together.
  • RFC 0470: 'fn-helper' captures the history behind the helper's design and has other example usage nuggets.