Permalink
Browse files

Create common function for attaching events and automatically detachi…

…ng them onbeforeunload
  • Loading branch information...
1 parent 0c6f888 commit 9896305a64536497df3974b10cdf85bff8eea4b8 Jason Johnston committed Oct 31, 2010
Showing with 15 additions and 17 deletions.
  1. +10 −0 sources/OnBeforeUnload.js
  2. +3 −9 sources/OnPrint.js
  3. +1 −4 sources/OnResize.js
  4. +1 −4 sources/OnScroll.js
@@ -3,3 +3,13 @@
*/
PIE.OnBeforeUnload = new PIE.Observable();
window.attachEvent( 'onbeforeunload', function() { PIE.OnBeforeUnload.fire(); } );
+
+/**
+ * Attach an event which automatically gets detached onbeforeunload
+ */
+PIE.OnBeforeUnload.attachManagedEvent = function( target, name, handler ) {
+ target.attachEvent( name, handler );
+ this.observe( function() {
+ target.detachEvent( name, handler );
+ } );
+};
View
@@ -4,8 +4,7 @@
*/
(function() {
- var elements,
- win = window;
+ var elements;
function beforePrint() {
elements = PIE.Element.destroyAll();
@@ -20,12 +19,7 @@
}
}
- win.attachEvent( 'onbeforeprint', beforePrint );
- win.attachEvent( 'onafterprint', afterPrint );
-
- PIE.OnBeforeUnload.observe( function() {
- win.detachEvent( 'onbeforeprint', beforePrint );
- win.detachEvent( 'onafterprint', afterPrint );
- } );
+ PIE.OnBeforeUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint );
+ PIE.OnBeforeUnload.attachManagedEvent( window, 'onafterprint', afterPrint );
})();
View
@@ -8,8 +8,5 @@
PIE.OnResize.fire();
}
- window.attachEvent( 'onresize', resized );
- PIE.OnBeforeUnload.observe( function() {
- window.detachEvent( 'onresize', resized );
- } );
+ PIE.OnBeforeUnload.attachManagedEvent( window, 'onresize', resized );
})();
View
@@ -9,10 +9,7 @@
PIE.OnScroll.fire();
}
- window.attachEvent( 'onscroll', scrolled );
- PIE.OnBeforeUnload.observe( function() {
- window.detachEvent( 'onscroll', scrolled );
- } );
+ PIE.OnBeforeUnload.attachManagedEvent( window, 'onscroll', scrolled );
PIE.OnResize.observe( scrolled );
})();

0 comments on commit 9896305

Please sign in to comment.