Where to put jQuery interactivity code

In both static sites and applications served by rails I’ve just placed jquery code in a separate js file for standard interactivity. For example, a function that sizes a container div to the exact size of the browser, or clicking a link and a drop down pops out instead of linking to another page – pretty standard stuff.

Where should I put these functions in my ember app?

I see I need the didInsertElement method in the corresponding template’s view. I’ve tried this:

Ew.IndexView = Ember.View.extend(didInsertElement: ->
  $(window).resize ->
    $(".home-bg").height $(window).height()
)

And in index.hbs I have:

<div class="row">
  <div class="large-12 columns home-bg">
    <h1>EW</h1>
</div>

I’m just using this home-bg class as a test to get it resize to the browser, but it’s only the height of the h1 tag.

Super weird…When I load the page the div is the height of the h1:

But as soon as I grab the corner of the browser to resize the div resizes to the size of the browser:

Again, here’s my resize function inside of index_view.coffee:

Ew.IndexView = Ember.View.extend(
  didInsertElement: ->
    $(window).resize ->
      $(".home-bg").height $(window).height()
)

Now that View has been removed in ember 2.0, any suggestion for using plain java scripts other than component’s didInsertElement hook

I think it really depends on what the “plain javascripts” are doing. If they’re manipulating the DOM for view/control reasons (IE jQuery plugins) they should be wrapped with a component. And that component should be included in a template. 2.0 Components have a range of hooks for different lifecycle events, but didInsertElement is generally appropriate for DOM updates.

If the plain javascripts are more data bound (IE Analytics, Realtime) you can, but don’t have to, wrap them in a service. Then if there is any initialization you can do it in your ApplicationRoute’s setupController hook.

It’s been a year since your last post, if you can tell me a bit more your use case I might be able to help you better.

1 Like