Skip to content

Instantly share code, notes, and snippets.

@foxnewsnetwork
Created January 20, 2016 00:22
Show Gist options
  • Save foxnewsnetwork/6bd4b08a55ed5a5c4321 to your computer and use it in GitHub Desktop.
Save foxnewsnetwork/6bd4b08a55ed5a5c4321 to your computer and use it in GitHub Desktop.
ember component modifying properties in didInsertElement hook

The Problem

Starting sometime in Ember 1.13.x, the core team decided that it shall be a bad idea to modify component variables inside the didInsertElement hook in Ember components. The explanation they gave was that it degrades performance (and who knows, perhaps it does, but I never notice because the 1000+ms waits for remote server to return data).

Nevertheless, modifying component properties on didInsertElement is often a necessity when (for example) we need to know the rendered dimensions of an element in order to perform some action:

didInsertElement: ->
  width = @$().width()
  @set "containerWidth", width
  @set "itemWidth", width
  @set "boundaryConditionsReady", true

It might be possible for me to cobble together some case-by-case solution that solves for the post-render sizes outside the component, then pass it in... but that's retarded and leads to retarded cancer code that degrades programmer productivity (which is far more important than computer performance).

The solution

It turns out, there's an easy fix - into the next run loop!

didInsertElement: ->
    run.next @, ->
      width = @$().width()
      @set "containerWidth", width
      @set "itemWidth", width
      @set "boundaryConditionsReady", true

Bam! No retarded code and no performance degredation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment