You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
openNG/lib/riot/mixins/on-child.js

58 lines
1.4 KiB
JavaScript

'use strict';
8 years ago
const riotQuery = require("riot-query");
const arrayDiff = require("arraydiff");
module.exports = {
8 years ago
init: function() {
let knownTags = [];
let listeners = {};
function triggerEvent(action, query, item) {
if (listeners[query] != null && listeners[query][action] != null) {
8 years ago
listeners[query][action].forEach((handler) => {
handler(item);
});
}
}
8 years ago
this.on("updated", () => {
Object.keys(listeners).forEach((query) => {
let currentTags = riotQuery(this, query);
let diff = arrayDiff(knownTags, currentTags);
8 years ago
diff.forEach((item) => {
if (item.type === "remove") {
8 years ago
for (let i = item.index; i < (item.index + item.howMany); i++) {
triggerEvent("remove", query, knownTags[i]);
}
} else if (item.type === "move") {
8 years ago
for (let i = item.index; i < (item.from + item.howMany); i++) {
triggerEvent("move", query, knownTags[i]);
}
} else if (item.type === "insert") {
8 years ago
item.values.forEach((value) => {
triggerEvent("create", query, value);
8 years ago
})
}
});
knownTags = currentTags;
});
});
8 years ago
this.onChild = function(eventName, handler) {
let [action, query] = eventName.split(":", 2);
if (listeners[query] == null) {
listeners[query] = {};
}
if (listeners[query][action] == null) {
listeners[query][action] = [];
}
listeners[query][action].push(handler);
8 years ago
}
}
8 years ago
}