hopglass/lib/datadistributor.js

94 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2015-07-08 21:17:00 +02:00
define(["filters/nodefilter"], function (NodeFilter) {
2016-05-27 23:59:01 +02:00
"use strict";
2015-07-08 00:36:57 +02:00
return function () {
var targets = [];
var filterObservers = [];
var filters = [];
var filteredData;
var data;
2015-07-08 00:36:57 +02:00
function remove(d) {
targets = targets.filter(function (e) {
return d !== e;
});
2015-07-08 00:36:57 +02:00
}
function add(d) {
targets.push(d);
2015-07-08 00:36:57 +02:00
if (filteredData !== undefined) {
d.setData(filteredData);
}
2015-07-08 00:36:57 +02:00
}
function setData(d) {
data = d;
refresh();
2015-07-08 00:36:57 +02:00
}
function refresh() {
if (data === undefined) {
return;
}
2015-07-08 00:36:57 +02:00
var filter = filters.reduce(function (a, f) {
2015-07-08 21:17:00 +02:00
return function (d) {
return a(d) && f.run(d);
};
}, function () {
return true;
});
2015-07-08 21:17:00 +02:00
filteredData = new NodeFilter(filter)(data);
2015-07-08 00:36:57 +02:00
targets.forEach(function (t) {
t.setData(filteredData);
});
2015-07-08 00:36:57 +02:00
}
function notifyObservers() {
filterObservers.forEach(function (d) {
d.filtersChanged(filters);
});
2015-07-08 00:36:57 +02:00
}
function addFilter(d) {
filters.push(d);
notifyObservers();
d.setRefresh(refresh);
refresh();
2015-07-08 00:36:57 +02:00
}
function removeFilter(d) {
filters = filters.filter(function (e) {
return d !== e;
});
notifyObservers();
refresh();
2015-07-08 00:36:57 +02:00
}
function watchFilters(d) {
filterObservers.push(d);
2015-07-08 00:36:57 +02:00
d.filtersChanged(filters);
2015-07-08 00:36:57 +02:00
return function () {
filterObservers = filterObservers.filter(function (e) {
return d !== e;
});
};
2015-07-08 00:36:57 +02:00
}
return {
add: add,
remove: remove,
setData: setData,
addFilter: addFilter,
removeFilter: removeFilter,
watchFilters: watchFilters,
refresh: refresh
};
};
});