Created
April 28, 2013 23:16
-
-
Save zachdunn/5478827 to your computer and use it in GitHub Desktop.
AngularJS Directive for easily attaching online & offline events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
angular.module('angularApp') | |
.directive('connectivity', ($window, $parse) -> | |
return ($scope, element, $attrs) -> | |
# Parse attribute value into JSON | |
events = $scope.$eval($attrs.connectivity) | |
# Loop through events in JSON object | |
angular.forEach events, (connEvent, eventName) -> | |
# Parse event | |
fn = $parse(connEvent) | |
# Attach events to listeners | |
switch eventName | |
when 'connect' | |
$scope.connect = fn | |
$window.addEventListener "online", -> | |
console.log 'Detect Online Event' | |
$scope.$apply -> | |
fn($scope) | |
when 'disconnect' | |
$scope.disconnect = fn | |
$window.addEventListener "offline", -> | |
console.log 'Detect Offline Event' | |
$scope.$apply -> | |
fn($scope) | |
# Run it once onload | |
if navigator.onLine | |
$scope.connect($scope) | |
else | |
$scope.disconnect($scope) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
Attach events through attribute object. | |
onConnect() and onDisconnect() are sample $scope functions | |
--> | |
<div connectivity="{connect: 'onConnect()', disconnect: 'onDisconnect()'}"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment