szurubooru/client/js/models/abstract_list.js

107 lines
2.6 KiB
JavaScript
Raw Normal View History

"use strict";
const events = require("../events.js");
class AbstractList extends events.EventTarget {
constructor() {
super();
this._list = [];
}
static fromResponse(response) {
const ret = new this();
for (let item of response) {
const addedItem = this._itemClass.fromResponse(item);
2016-07-22 13:27:52 +02:00
if (addedItem.addEventListener) {
addedItem.addEventListener("delete", (e) => {
2016-07-22 13:27:52 +02:00
ret.remove(addedItem);
});
addedItem.addEventListener("change", (e) => {
ret.dispatchEvent(
new CustomEvent("change", {
detail: e.detail,
})
);
2016-07-22 13:27:52 +02:00
});
}
ret._list.push(addedItem);
}
return ret;
}
2017-10-01 21:46:53 +02:00
sync(plainList) {
this.clear();
for (let item of plainList || []) {
2017-10-01 21:46:53 +02:00
this.add(this.constructor._itemClass.fromResponse(item));
}
}
add(item) {
2016-07-22 13:27:52 +02:00
if (item.addEventListener) {
item.addEventListener("delete", (e) => {
2016-07-22 13:27:52 +02:00
this.remove(item);
});
item.addEventListener("change", (e) => {
this.dispatchEvent(
new CustomEvent("change", {
detail: e.detail,
})
);
2016-07-22 13:27:52 +02:00
});
}
this._list.push(item);
const detail = {};
detail[this.constructor._itemName] = item;
this.dispatchEvent(
new CustomEvent("add", {
detail: detail,
})
);
}
2016-07-22 13:27:52 +02:00
clear() {
for (let item of [...this._list]) {
this.remove(item);
}
}
remove(itemToRemove) {
for (let [index, item] of this._list.entries()) {
if (item !== itemToRemove) {
continue;
}
this._list.splice(index, 1);
const detail = {};
detail[this.constructor._itemName] = itemToRemove;
this.dispatchEvent(
new CustomEvent("remove", {
detail: detail,
})
);
return;
}
}
get length() {
return this._list.length;
}
2016-07-22 13:27:52 +02:00
at(index) {
return this._list[index];
}
2017-10-01 21:46:53 +02:00
map(...args) {
return this._list.map(...args);
}
filter(...args) {
return this._list.filter(...args);
}
[Symbol.iterator]() {
return this._list[Symbol.iterator]();
}
}
module.exports = AbstractList;