Search code examples
jquerybackbone.jsmarionettejquery-eventsbackbone-events

Backbone.js - custom JQuery event


I have problem with Backbone (Marionette) and jQuery custom DOM event.

I have custom plugin, that updates html content of element when changed_currency event is fired on document.

$(document).on
  changed_currency: ->
    # omitted code
    $(@).html("some html")
, '.currency-change'

Nothing fancy here. It works on pages that don't use Backbone. However, when in backbone view, this code don't work at all (event is not caught). So my question is, can I fire custom event from inside of my Backbone view?

Backbone code:

#omitted code
ui: 
   currency_change: '.currency_change'

onRender: () =>
  #omitted code
  @ui.currency_change.trigger('changed_currency')

Solution

  • This doesn't work because the onRender function is called at the end of the Marionette implementation of the render function. The render function renders the view's HTML into an element that is not part of the DOM.

    It is not until you actually insert it into the DOM that your event handler that is hanging off of document will capture the event you triggered.

    If you are taking advantage of Marionette's region concept then you can solve your problem by moving the trigger call to the onShow function. Otherwise, you will need to move the trigger call to be after wherever you actually insert the view.el into the DOM.

    // In view
    onShow : function () {
      this.ui.currency_change.trigger('changed_currency');
    }
    
    // View instantiation code
    var view = new SomeView();
    App.someRegion.show(view);