Backbone.js 如何让触发器正确监听
我很难让我的触发器做出正确的反应。我有很多工作,但其中一个没有,我不明白为什么 这是我的AppController类Backbone.js 如何让触发器正确监听,backbone.js,backbone-events,eventtrigger,Backbone.js,Backbone Events,Eventtrigger,我很难让我的触发器做出正确的反应。我有很多工作,但其中一个没有,我不明白为什么 这是我的AppController类 class ProjectOrder.View.AppController extends Backbone.View initialize: -> @promptOfficeSearch() promptOfficeSearch: -> officeSearch = new ProjectOrder.View.OfficeSearch
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对象,它不会响应CreateTicketOffFaccount事件,该事件在my OfficeCreator类的submitOffice ajax成功回调中注册:
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()
})
你知道我的触发器为什么不工作吗?我想你需要在你的
AppController
类中的所有方法上加上粗箭头
此事件激发时:
officeSearch.on 'createOffice', @promptOfficeCreate
promptOfficeCreate
函数作为普通函数调用,而不是作为this
绑定到控制器实例的方法调用,因此发生这种情况时:
officeCreate.on 'createTicketOffAccount', @promptTicketCreate
@prompticketcreate
未定义,事件绑定未正确连接。我没有将事件处理程序绑定到模型实例。它绑定到了officeCreate的一个实例(它是一个主干视图)officeCreate
。是的,你完全正确。该方法在错误的对象上被调用,失去了AppController上此的焦点。谢谢你的帮助!