Ember.js - The Ember Times - Issue No. 110

Aloha Emberistas! 🐹

This week: {{on}} & {{fn}} in Octane Guides 🔥, Foreign Key Attrs Blog Post 🔑, watch This.JavaScript: State of Frameworks on Tuesday 📜, build JAMstack websites with Empress 🍓, versioned Ember API links added to the Guides 🔢, and last, but not least, an Update for Co-Located Templates in the Guides ☝️!

This is a companion discussion topic for the original entry at https://emberjs.com/blog/2019/08/09/the-ember-times-issue-110.html
1 Like

What’s the recommended way to use fn helper? I know that it’s optional but I feel that there are values for explicitly stating that what you’re passing is an action/function:

  1. It seems Ember is already headed toward the explicit experience (e.g. with @arg, this.prop, @tracked, etc.) so why not continue with it?
  2. You get an immediate error when {{fn this.functionDoesNotExist}} as opposed to {{this.functionDoesNotExist}} which will only error out when invoked.
  3. It’s easier to spot out and distinguish props vs actions in a template.
  4. It’s easier to refactor. I was able to do this quickly by just doing a search and replace for {{action to {{fn.
  5. Less learning curve. If you’re passing an action, just use {{fn}}. No need to teach that it’s only used when you need to pass some params. This also avoids the nitpicks in code-reviews like you don’t need to use {{fn}} since we’re not passing any params.

{{fn}} does NOT bind the this context, so it’s not a replacement for {{action}} (in HBS) or @action (in JS).

The reason to use fn is to partially apply arguments from handlebars. For example:

<button {{on "click" (fn this.myMethod 123)}}>Click me</button>

Now, in myMethod, the first argument is 123, but this is not the same JS context:

  myMethod(arg1) {
    myArg // 123
    this // something other than the class/component myMethod is defined in

This technique can be useful for all the same reasons partial application (or currying) is useful when passing around functions to places you don’t control. (This is a googleable paradigm, but if you need a more specific example for Handlebars / templating / Ember, I can try to cook something up. I’ve definitely used partial application from templates especially when designing low level components that accept functions as arguments).

Yeah I get those binding concepts.

I worded it wrong. My question is that would it be better to just flat out recommend using {{fn}} even without params due to the reasons I’ve indicated in my previous post.

I’m asking this because the Octane guides seems to be recommending the opposite.

Ah I understand your question better now, sorry I misread.

I don’t see a problem with always using fn other than that it’s verbose for the majority of cases where no arguments are being partially applied.

I can see the benefit of scanning a template and knowing what’s a function and what’s a property, but I feel like it should also mostly be obvious.