Subscribe to DOM events


#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')
});

#2

You should put that in the view instead. There are hooks for these types of needs.

import Ember from 'ember';

export default Ember.View.extend({

    bindResize: function(){
        // Ensure DOM changes have been applied
        Ember.run.schedule('afterRender', this, function(){
            this.$('.post-content img').on('click', this.resizeImage);
        });
    }.on('didInsertElement'),

    unbindResize: function(){
        // Remove event bindings before "un-rendered"
        this.$('.post-content img').off('click', this.resizeImage);
    }.on('willDestroyElement'),

    resizeImage: function(){
        // RESIZE HERE
    }

});

#3

Or you can build a component/view for the image itself and attach an action handler.

For instance: https://github.com/runspired/smoke-and-mirrors/blob/master/addon/components/async-image/component.js