Skip to content

Instantly share code, notes, and snippets.

@zachdunn
Created April 28, 2013 23:16
Show Gist options
  • Save zachdunn/5478827 to your computer and use it in GitHub Desktop.
Save zachdunn/5478827 to your computer and use it in GitHub Desktop.
AngularJS Directive for easily attaching online & offline events
'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)
)
<!--
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