如何在骨干文章中添加resize事件?

时间:2012-06-28 23:00:10

标签: backbone.js coffeescript backbone-events

events:
    'click textarea': 'composeComment'
    'click .submit': 'submit'
    'blur textarea': 'textareaBlur'
    'resize article': 'repositionBoards'


repositionBoards: ->
    #this is my own function, i just need it to be called everytime an article's size changes
    board.align()

如何在调整大小事件时调用repositionBoards方法?

1 个答案:

答案 0 :(得分:8)

resize event已发送至window

  

当浏览器窗口大小发生变化时,resize事件将发送到window元素

但是Backbone视图的事件使用delegate绑定到视图的el。视图el不会收到resize个事件,因此将'resize articule': 'repositionBoards'放入视图events中将无效。

如果您需要在视图中获取resize事件,则必须自己将其绑定到window

initialize: (options) ->
    $(window).on('resize', this.repositionBoards)
remove: ->
    $(window).off('resize', this.repositionBoards) # Clean up after yourself.
    @$el.remove() # The default implementation does this.
    @
repositionBoards: ->
    # Use => if you need to worry about what `@` is
    board.align()

另请注意添加remove,以便您可以取消绑定resize处理程序。当然,您将要使用view.remove()删除您的视图,或者如果该视图是您的整个应用程序,请不要担心。