在jQuery UI Widget上绑定内部事件侦听器



TLDR

我正试图以与外部处理程序相同的方式进行绑定,只是在jQueryUIWidget的内部。

详细信息

为了触发/监听大型/可插入jQuery UI Widget内部的事件,我尝试使用小部件元素的bind和小部件的_trigger,但似乎无法正确连接。

以下代码来自小部件内的一个coffescript类,该类有一个对它的反向引用:

  bind: (type, fn) ->
    ### bind a callback through the widget's element ###
    # this doesn't work
    @widget.element.bind("#{@widget.widgetEventPrefix}#{type}", fn)
    # this doesn't work either
    @widget.element.bind(type, fn)

以下内容无效:

@widget._trigger('foo')

原因

我绑定了错误的元素。我注意到@widget.element与用作小部件外部引用的元素不同,例如@widget.element!==$('#bar').myWidget()

摘要

外部侦听器通过$('#bar').myWidget().bind('mywidgetfoo', () -> alert 'foo') 以相同的方式绑定/侦听没有问题

我正试图以与外部处理程序相同的方式进行绑定,只是在小部件的内部。

问题

我应该如何在小部件内部进行绑定,以便正确连接内部和外部侦听器?

IFINALLY弄清楚了这一点,它很简单,因为忽略了使用bind侦听的处理程序都是小写的事实。

因此,这里是我在内部组件基类中使用的代码示例,该代码允许组件针对顶级jQueryUIWidget进行bindunbind,从而允许我使用面向事件的体系结构,该体系结构在小部件内外使用相同的事件:

class Base
  constructor: (@widget) ->
  _fullyQualifiedEventName: (type) ->
    fullyQualifiedName = "#{@widget.widgetEventPrefix}#{type}".toLowerCase()
    fullyQualifiedName  
  bind: (type, fn) ->
    ### bind a callback through the widget's element ###
    fullyQualifiedName = @_fullyQualifiedEventName(type)
    @widget.element.bind(fullyQualifiedName, fn)
    console.log "bind(#{fullyQualifiedName}, #{fn.name})"
  unbind: (type, fn) ->
    ### unbind a callback from the widget's element ###
    fullyQualifiedName = @_fullyQualifiedEventName(type)
    @widget.element.unbind(fullyQualifiedName, fn)
    console.log "unbind(#{fullyQualifiedName}, #{fn.name})"

无论内部的处理程序是用@bind('foo', fn)绑定到foo事件,还是用$('#bar').myWidget().bind('mywidgetfoo', fn)绑定到外部,或者它们通过实例化{foo: () -> console.log 'options foo listener fired'}中的选项传入处理程序,所有侦听器现在都将用@widget._trigger('foo') 触发

最新更新