1

I've got a Ember CLI based blog. I currently resize all <img> inside posts upon clicking them using this function inside the application-controller.

I rely on on('init') and Ember.run.later and this feels just dirty.

How can I improve the subscription code below?

import Ember from 'ember';

export default Ember.ArrayController.extend({
  imageScaling: function() {
    Ember.run.later((function() { 
      //Subscribe to the actual event
      Ember.$(".post-content img").on("click", function(){
        // RESIZE HERE
      })
    }), 3000)
  }.on('init')
});
Hedge
  • 16,142
  • 42
  • 141
  • 246

1 Answers1

2

If you're inserting all of your images inside Ember templates, you can always use the action helper:

<img {{action 'scaleImages' on='click'}} src='' />

I realize that's probably not the case though. The way I've dealt with DOM interactions in the past is to override the application view then set up and tear down my event handler there. You can also avoid the Ember.run.later call by modifying your jQuery event listener. Here's how I would do it:

// app/views/application.js
export default Ember.View.extend({
    setupImageScaling: function() {
        $('body').on('click.image-scaling', 'img', function() {
            // RESIZE HERE
        });
    }.on('didInsertElement'),

    teardownImageScaling: function() {
        $('body').off('click.image-sacling');
    }.on('willDestroyElement')
});

In my opinion, the above is the 'most Ember' way of handling this kind of situation.

GJK
  • 37,023
  • 8
  • 55
  • 74
  • Thanks for the solution. I hope for a more Ember-ish way to handle this :( – Hedge Apr 01 '15 at 16:07
  • Ember does a great job at Handling things when you let Ember handle _everything_. When you do things outside of Ember (like insert images into the DOM without using an Ember template), things start to get a little less pretty. Fortunately, you shouldn't have to do things like this very often. – GJK Apr 01 '15 at 16:09
  • I'm having problems like this quite often currently because I render nice HTML/behaviour inside my blog posts which would make great components but I can't replace more than one [mycomponent] in my posts :( See here http://stackoverflow.com/questions/29265024/insert-partial-component-at-dynamic-location – Hedge Apr 01 '15 at 16:14
  • Most of this logic should go inside that component then. When integrating with external libraries/HTML, best practice is to try to isolate that code to a component. (You can do the same thing as above though, since components extend views.) It looks a bit ugly, but since you're generating the HTML elsewhere, there's not much Ember can do for you automatically. – GJK Apr 01 '15 at 16:27