I have an Angular state which can rotate between three templates each controlled by its own directive. The directives have event listeners, but as I rotate through the directives the event listeners add up by one and after the first transition to another directive everything starts to get buggy. I have attempted to fix these bugs but to no avail. Here is an example of one of the three directives:
angular.module('app').directive('presetStationOne', function($interval, $parse, $compile, PresetFactory){
var linker = function(scope, element, attrs){
PresetFactory.assign(1,6,scope);
scope.$watch('page1', function(newVal, oldVal){
if(newVal === true) {
allEncompassing(document, PresetFactory, scope, "start");
}
});
scope.$on('$destroy', function(){
allEncompassing(document, PresetFactory, scope, "finish");
});
};
return {
restrict: 'EA',
scope: false,
link: linker,
templateUrl: 'public/templates/freeplay/presetspage1.html'
};
});
And here is the function allEncompassing()
, which is all three presetStation directives. They all use PresetFactory and when I change from one directive to another, the calls on PresetFactory incrementally increase.
function allEncompassing(document, PresetFactory, scope, msg){
if (msg === "finish"){
removeMyListeners();
}
function clickListen(e){
var f;
if (!e.target.attributes.stationnumber){
if (undefined){
return;
} else if(!e.target.parentNode || !e.target.parentNode.parentNode || !e.target){
return;
} else if (!e.target.parentNode.parentNode.attributes.hasOwnProperty('stationnumber')){
return;
} else {
return f = e.target.parentNode.parentNode.attributes;
}
} else {
return f = e.target.attributes;
}
}
function resetMouseup(PresetFactory){
restartMyListeners();
PresetFactory.mouseUp();
}
function execMouseup(e){
resetMouseup(PresetFactory);
}
function execClickListen(e){
var f = clickListen(e);
if (f !== undefined){
PresetFactory.mouseDown(f, scope);
scope.$digest();
restartMyListeners();
} else {
return;
}
}
function restartMyListeners(){
restartMousedown();
document.removeEventListener('mouseup', execMouseup);
document.addEventListener('mouseup', execMouseup);
}
function restartMousedown(){
document.removeEventListener('mousedown', execClickListen);
document.addEventListener('mousedown', execClickListen);
}
function removeMyListeners(){
document.removeEventListener('mousedown', execClickListen);
document.removeEventListener('mouseup', execMouseup);
}
if (msg === "start"){
restartMyListeners();
}
}
What is the best way to mitigate increasing these event listeners and keep it to a single event listener?