Skip to content

Instantly share code, notes, and snippets.

@fpillet
Created May 7, 2013 13:46
Show Gist options
  • Save fpillet/5532684 to your computer and use it in GitHub Desktop.
Save fpillet/5532684 to your computer and use it in GitHub Desktop.
Experimental Page Flip Monitor module for CommandFusion iViewer
/* PageFlipMonitor v1.0
* Copyright 2013 CommandFusion, public domain
*
* Utility object that monitors entering and exiting pages,
* and can call any number of callbacks specifically registered to observe
* when entering or exiting a page
*
* You callback functions should be of the form:
*
function callback(fromPage, toPage) {
// do your processing here
}
*
* To monitor page flips, call watchEnter or watchExit. Each function returns a unique ID that allows
* you to later unregister the watch
*
* var watch1 = PageFlipMonitor.watchEnter("Page 1", myEnterCallback); // be notified when entering "Page 1"
* var watch2 = PageFlipMonitor.watchExit("Page 1", myExitCallback); // be notified when exiting "Page 1"
*
* // to stop watching:
*
* PageFlipMonitor.unwatch(watch1);
* PageFlipMonitor.unwatch(watch2);
*
*/
var PageFlipMonitor = {
nextID: 0,
enter: {},
exit: {},
watchEnter: function(pageName, callback) {
return this.register(this.enter, pageName, callback);
},
watchExit: function(pageName, callback) {
return this.register(this.exit, pageName, callback);
},
unwatch: function(id) {
function filter(watchSet) {
for (var pageName in watchSet) {
if (watchSet.hasOwnProperty(pageName)) {
watchSet[pageName] = watchSet[pageName].filter(function(e) {
return e.id != id;
});
}
}
}
filter(this.enter);
filter(this.exit);
},
// internal function, do not use
register: function(watchSet, pageName, callback) {
function doCallbacks(array, from, to) {
if (array != null) {
array.forEach(function(elem) {
try {
elem.cb.apply(null, from, to);
}
catch(e) {
CF.log("Warning: exception caught while calling Page Flip callback from " + from + " to " + to + ": " + e);
}
});
}
}
var array = watchSet[pageName];
if (array == null) {
array = [];
watchSet[pageName] = array;
}
if (this.nextID == 0) {
var self = this;
CF.watch(CF.PageFlipEvent, function(from, to) {
if (from != null)
doCallbacks(self.exit[from], from, to);
if (to != null)
doCallbacks(self.enter[to], from, to);
});
}
var id = this.nextID++;
array.push({
id: id,
cb: callback
});
return id;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment