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

若如初见. 提交于 2019-12-13 04:51:50

问题


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.


回答1:


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')



回答2:


If a view have the document as view.el, then you could listen to custom DOM events using the events hash.

If not, then you can listen to an event manually in the initialize method.

initialize: function() {
    $(document).on("visibilitychange", _.bind(this.hanldeVisibility, this));
}

This will work, so if it haven't for you, it can be a race condition (check any async behavior, etc).

On an important side note. It is really important to clear custom binded events once your view is removed. This is usually handle this way:

remove: function() {
    Backbone.View.prototype.remove.call(this);
    $(document).off("visibilitychange");
}

If you do not clean your events after, you'll create memory leaks. And this could eventually crash your application.



来源:https://stackoverflow.com/questions/19575071/backbone-js-with-custom-events-in-view-events-from-another-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!