如何让触发器正确收听

时间:2013-08-01 20:46:33

标签: backbone.js backbone-events eventtrigger

我很难让我的触发器正确响应。我有很多工作,但其中一个不是,我不明白为什么。

这是我的AppController类

class ProjectOrder.View.AppController extends Backbone.View
  initialize: ->
    @promptOfficeSearch()

  promptOfficeSearch: ->
    officeSearch = new ProjectOrder.View.OfficeSearch
    officeSearch.on 'createOffice', @promptOfficeCreate
    officeSearch.on 'createTicket', @promptTicketCreate
    officeSearch.on 'accountAndTicketExist', @killProcessAccountExists


 promptOfficeCreate: (serial) ->
   @officeModel = new ProjectOrder.Model.OfficeModel()
   @officeModel.set('serial_number', serial)

   officeCreate = new ProjectOrder.View.OfficeCreator({model: @officeModel})
   officeCreate.on 'createTicketOffAccount', @promptTicketCreate

 promptTicketCreate: (model) ->
   console.log 'promptTicketCreate'
   model = model || @officeModel
   ticketModel = new ProjectOrder.Model.TicketModel()
   new ProjectOrder.View.TicketCreator({ticketModel: ticketModel, officeModel: model})

 killProcessAccountExists: (ticket_id) ->
   msg = document.createElement 'div'
   msg.className = 'account-exists-msg'
   msg.innerHTML = "Account already exists. Redirecting to ticket #{ticket_id}..."

   $('#create-order-div').append(msg)
   setTimeout((->
     window.location = "/pto/#{ticket_id}"
   ), 2000)

promptOfficeSearch函数中officeSearch对象的所有触发器都能正常工作。它们分别按以下方式触发:

@trigger 'createOffice', serial
@trigger 'createTicket', data.model[0]
@trigger 'accountAndTicketExist', data.model

但是对于promptOfficeCreate中的officeCreate对象,它不会响应在我的OfficeCreator类的submitOffice ajax成功回调中注册的createTicketOffAccount事件:

class ProjectOrder.View.OfficeCreator extends Backbone.View
  template: _.template($("#OfficeCreator").html())
  id: 'office-creator'
  events:
    'click .submit'     : 'submitOffice'

  initialize: ->
    @render()

  render: ->
    @$el.html(@template(@model.toJSON()))
    $('#create-order-div').append(@$el)

  submitOffice: ->
    @setModelData()
    @model.save(null,{
      success: (model) =>
        @trigger 'createTicketOffAccount', model
        #@$el.remove()
      error: ->
        alert 'error'
    })

  setModelData: ->
    @model.set({
      office_name:    $('#office').val()
      doctor_name:    $('#doctor').val()
      emr:            $('#has-emr').is(':checked')
      forms_builder:  $('#has-forms').is(':checked')
      iehr:           $('#has-iehr').is(':checked')
      clipboard:      $('#has-clip').is(':checked')
      specialty_id:  $('#specialty').val()
    })

我的触发器无效的任何想法?

1 个答案:

答案 0 :(得分:1)

我认为你AppController班的所有方法都需要胖箭头。

当此事件触发时:

officeSearch.on 'createOffice', @promptOfficeCreate

promptOfficeCreate函数作为普通函数被调用,而不是作为this绑定到控制器实例的方法,所以当发生这种情况时:

officeCreate.on 'createTicketOffAccount', @promptTicketCreate

@promptTicketCreate未定义且事件绑定未正确连接。