thefrontside / ember-let

Create variable bindings inside your handlebars templates
MIT License
52 stars 16 forks source link

consider key="" semantics? #29

Open machty opened 7 years ago

machty commented 7 years ago

Another possibly dumb proposal:

http://emberjs.com/api/classes/Ember.Templates.helpers.html#toc_specifying-keys

Ember's #each helper let's you specify an optional key= param for reconciling values/elements before and after a render, such that if an array element after a render has a key that matches one before render, the component will be reused, won't be rebuilt, etc.

I've found that sometimes I want this in a non-array context; I want to be able to opt into re-rendering a component if a value driving it has changed, since in some cases this keeps the component logic simpler; I don't have to know any special and maybe-likely-to-be-changed didUpdateAttrs hooks and what not, I just have to write a component and implement didInsertElement. I wanted this when implementing a singleton tooltip that set it's location depending on the currently active element that was passed into it; because this feature didn't exist I had to resort to observers which don't have the benefit of the debounced render timing that most component rendering falls into.

So anyway it might be nice if ember-let had a key= option with similar semantics as the each helper. The default value would be @index, which is to say let is basically an each against a single element array with the value you're letting. But it could be changed to @identity to re-render the block and any components inside it if the object is switched out in any way, or it could be some property of the object from which a key should be derived.

This would basically close the gap between Ember's each-specific concept of keys vs React's universal concept of keys.

{{#let activeElement key="@identity" as |el|}}
  {{tooltip-that-gets-totally-rerendered-whenever-el-changes el=el}}
{{/let}}
machty commented 7 years ago

Here's what I mean: https://ember-twiddle.com/be37e5d6b5297eee14280eafb06d938c?openFiles=templates.application.hbs%2Ctemplates.components.better-let.hbs