Search code examples
backbone.jsbackbone-eventssteroids

Backbone.js with custom events in VIEW (events from another library)?


So I am using steroids.js and the library provides me with this event:

document.addEventListener("visibilitychange", onVisibilityChange, false);

function onVisibilityChange() {

}

This works if I just put it in my JS file, but how does that translate in a View with Backbone.js? How I implement this with the framework? I tried with .on in the initialize function, but it does not seem to work.


Solution

  • 1 - Using document as an element:

    var DocumentEventsView = Backbone.View.extend({
      el : document,
      events : {
        'visibilitychange' : 'onVisibilityChange'
      },
      onVisibilityChange : function () {
        console.log('inside onVisibilityChange');
      }
    });
    
    // test
    new DocumentEventsView();
    $(document).trigger('visibilitychange');
    

    2 - Using custom el:

    var DocumentEventsView = Backbone.View.extend({
      initialize : function () {
        $(document).on('visibilitychange', _.bind(this.onVisibilityChange, this));
      },
      onVisibilityChange : function () {
        console.log('inside onVisibilityChange');
      }
    });
    
    // test
    new DocumentEventsView();
    $(document).trigger('visibilitychange')