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)
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.
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.
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')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With