Search

8/24/2012

backbone tricks

1. _.bind, $.proxy的作用
2. 怎樣再 initialize 呼叫 event handler 並維持本來的 execution scope
3. 怎樣針對 mobile browser 用 'touchstart' event 而不是 'click' evnet

  FooView = Backbone.View.extend(
    el: $('#main')
  
    initialize: ->

      
      if navigator.userAgent.match(/(iphone|ipod|ipad|android)/i)
        $('#frames .frame').on('touchstart', _.bind(@handleFrameClick, @))
        $('#controller').on('touchstart', '.icon-play-circle', _.bind(@play, @))
        $('#controller').on('touchstart', '.icon-th-large', _.bind(@toggleFilmMode, @))
        $('#controller').on('touchstart', '.icon-sign-blank', _.bind(@toggleFilmMode, @))
      else
        $('#frames .frame').on('click', _.bind(@handleFrameClick, @))
        $('#controller').on('click', '.icon-play-circle', _.bind(@play, @))
        $('#controller').on('click', '.icon-th-large', _.bind(@toggleFilmMode, @))
        $('#controller').on('click', '.icon-sign-blank', _.bind(@toggleFilmMode, @))

    events:
      'change #range': 'rangeChange'
  )


  new FooView
其中
    events:
      'click #frames .frame': 'handleFrameClick'
      'click #controller .icon-play-circle': 'play'
      'click #controller .icon-th-large': 'toggleFilmMode'
      'click #controller .icon-sign-blank': 'toggleFilmMode'
要放在 initialize 要寫成
        $('#frames .frame').on('click', _.bind(@handleFrameClick, @))
        $('#controller').on('click', '.icon-play-circle', _.bind(@play, @))
        $('#controller').on('click', '.icon-th-large', _.bind(@toggleFilmMode, @))
        $('#controller').on('click', '.icon-sign-blank', _.bind(@toggleFilmMode, @))
_.bind(@handleFrameClick, @)可以改變 @handleFrameClick 裡面 this 的值, 作法跟 $.proxy(@handleFrameClick, @) 是一樣的

沒有留言: