我应该如何绑定到Ember View中的窗口函数?

Bra*_*est 10 ember.js

我有一个mixin自动重新计算并设置页面调整大小的div的高度.

它可以工作,但是每次调用它时绑定到jQuery事件并手动触发Ember事件对我来说似乎很愚蠢.

有没有办法直接绑定到Ember的窗口事件?

在这里有一个简化的JSFiddle

这是代码:

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')
)
Run Code Online (Sandbox Code Playgroud)

而调用它的mixin.

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)
Run Code Online (Sandbox Code Playgroud)

Ita*_*mid 14

我知道我已经晚了几年,但我一直在寻找解决同样问题的方法,并发现了这个:

jQuery(window).on('resize', Ember.run.bind(this, this.handleResize));
Run Code Online (Sandbox Code Playgroud)

(来源:Ember.js ofiicial)

****PS关于这个小技巧的实现 - 我不知道是否可以在控制器方法中使用它并在init上触发(如denis.peplin所评论),我实际上是绑定路径中的事件'setupController'功能.我不知道这是不是最好的做法,但它在我的应用程序中就像一个魅力.


ebr*_*ryn 8

使用jQuery为这样的事情注册自己的事件处理程序没有任何问题.

Ember目前没有任何窗口事件处理.

我还建议尝试提出一种不依赖于全局变量的解决方案.