Angular event and action timer

Angular 2 is already in Beta but I am now still working on a project with ionic which is based on angular 1.4.3. Maybe too late but there are two small pieces of code I think worthing sharing, so I put them into two tiny libs for angular 1: angular-event and angular-action-timer.

angular-event

Some people are using $rootScope.$emit() for event based communication. angular-event is basicly a wrapper arount it but no more string event names typing around.

Use as global events

Define the event service

1
2
3
4
5
6
angular.module('demo')
.factory('evtDemoTriggered', evtDemoTriggered);

function evtDemoTriggered(event) {
return event('demo:triggered');
}

Inject and dispatch the event

1
2
3
4
5
6
7
8
angular.module('demo')
.factory('demoTrigger', demoTrigger);

function demoTrigger(evtDemoTriggered) {
function trigger() {
evtDemoTriggered.emit();
}
}

Inject and listen to the event

1
2
3
4
5
6
7
8
9
angular.module('demo')
.factory('demoModel', demoModel);

function demoModel(evtDemoTriggered) {
evtDemoTriggered.on(onDemoTriggered);
function onDemoTriggered() {
//...
}
}

Use as an instance event

Define and dispatch the instance event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
angular.module('demo')
.factory('demoModel', demoModel);

function demoModel(event) {
var model = {
value: 0,
evtUpdate: event('demo:model:update')
};
return model;

function demo() {
model.value++;
model.evtUpdate.emit(model.value);
}
}

Inject and listen to the event

1
2
3
4
5
6
7
8
9
angular.module('demo')
.controller('demoController', demoController);

function demoController(demoModel) {
demoModel.evtUpdate.on(onModelUpdate);
function onModelUpdate(event, value) {
alert('Model updated: ' + value);
}
}

angular-action-timer

angular-action-timer is a wrapper of $timeout and useful when some function needs to be invoked after user “stop” doing something continually. Here is a Demo for it working together with angular-event.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
angular.module('demo', ['ng.event', 'ng.actionTimer'])
.factory('demoTrigger', demoTrigger);

function demoTrigger(evtDemoTriggered, actionTimer) {
var timer = actionTimer(trigger, 500);
return {
execute: execute
};

function execute() {
timer.schedule();
}

function trigger() {
evtDemoTriggered.emit();
}
}