Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I bind to a window function in an Ember View?

Tags:

ember.js

I have a mixin which automatically recalculates and sets the height of a div on page resize.

It works but it seems silly to me to be binding to a jQuery event and triggering an Ember event manually every time it is called.

Is there a way to bind to window events directly in Ember?

I have a simplified JSFiddle here

This is the code:

App.windowWrapper = Ember.Object.create(Ember.Evented,
  resizeTimer: null
  init: ->
    @_super()
    object = this
    $(window).on 'resize', ->
      window.clearTimeout(object.resizeTimer)
      object.resizeTimer = setTimeout( App.windowWrapper.resize, 100)
      true

  resize: ->
    App.windowWrapper.fire('resize')
)

And the mixin that is calling it.

App.Scrollable = Ember.Mixin.create
  classNames: "scrollable"
  init: ->
    Ember.assert("Scrollable must be mixed in to a View", this instanceof Ember.View)
    @_super()

  didInsertElement: ->
    @_super()
    @calculateHeight()
    App.windowWrapper.on('resize', this, 'calculateHeight')

  willDestroyElement: ->
    App.windowWrapper.off('resize', this, 'calculateHeight')
    @_super()

  calculateHeight: ->
    offset       = @$().offset().top
    windowHeight = $(window).height()
    @$().css('height', windowHeight - offset)
like image 349
Bradley Priest Avatar asked Jun 01 '12 01:06

Bradley Priest


3 Answers

I know I'm a few years late, but I was looking for a solution to the same problem and found this:

jQuery(window).on('resize', Ember.run.bind(this, this.handleResize));

(source: Ember.js ofiicial)

**** P.S. About the implementation of this little trick - I don't know if it's possible to use it in a controller method and trigger on init (as denis.peplin commented), I'm actually binding the event in the route's 'setupController' function. I don't know if it's best-practice, but it works like a charm in my app.

like image 152
Itay Hamashmid Avatar answered Nov 01 '22 14:11

Itay Hamashmid


There's nothing wrong with registering your own event handler with jQuery for something like this.

Ember doesn't have any window event handling currently.

I'd also suggest trying to come up with a solution that didn't rely on globals.

like image 43
ebryn Avatar answered Nov 01 '22 14:11

ebryn


And sample code for Itay Hamashmid's answer:

App.ApplicationController = Ember.Controller.extend({
  handleResize: function() {
    console.log('resized');
  },
  bindResizeEvent: function() {
    jQuery(window).on('resize', Ember.run.bind(this, this.handleResize));
  }.on('init')
});
like image 43
denis.peplin Avatar answered Nov 01 '22 14:11

denis.peplin