Skip to content

Instantly share code, notes, and snippets.

@sprin
Created January 27, 2014 04:18
Show Gist options
  • Save sprin/8643219 to your computer and use it in GitHub Desktop.
Save sprin/8643219 to your computer and use it in GitHub Desktop.
Backbone VisEventsView
var VisEventsView = Backbone.View.extend({
// A Backbone.View extension that allows a View to trigger events when
// it's visibility changes. The view may also listen to its own visibility
// events.
setup_visibility_observer: function() {
// Check if view element is visible when attributes of el change.
var t = this;
_.bindAll(t, 'check_visibility');
t.visibility_observer = new MutationObserver(t.check_visibility);
t.visibility_observer.observe(t.el, {attributes: true});
},
setup_dom_insertion_observer: function() {
// Check if view element is visible when DOM elements are
// inserted or removed.
var t = this;
_.bindAll(t, 'check_visibility');
t.insertion_observer = new MutationObserver(t.check_visibility);
t.insertion_observer.observe(document, {childList: true, subtree: true});
},
check_visibility: function() {
var t = this;
var visible = t.$el.is(":visible");
if (visible) {
// If currently visible, and hidden as of last mutation,
// fire `visible` event and set visibility to true.
if (t.visibility !== true) {
t.visibility = true;
t.trigger('visible');
}
} else {
// If currently not visible, and visible as of last mutation,
// fire `hidden` event and set visibility to false.
if (t.visibility !== false) {
t.visibility = false;
t.trigger('hidden');
}
}
},
});
@sprin
Copy link
Author

sprin commented Feb 8, 2014

Not recommended for performance reasons in apps with lots of DOM mutation. It should be possible to improve performance by defining the MutationObserver to be more specific, rather than listening to document and it's subtree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment