datastore
коллекция методов datastore
object datastore;
Details
Примечание, задачи (Tasks) и связи (Links) следует управлять через стандартный API Gantt. Прямые изменения задач или связей внутри datastore могут привести к непредвиденным проблемам. Datastore в основном предназначены для ресурсов или других пользовательских объектов.
Вы можете создать новый datastore с помощью метода createDatastore.
Объект datastore предоставляет следующие методы и события:
Методы
-
parse (data): void - загружает данные из массива
- data - (Array<object>) - данные для загрузки
gantt.$resourcesStore.parse([
{id: 1, text: "QA", parent:null},
{id: 2, text: "Development", parent:null},
{id: 3, text: "Sales", parent:null},
{id: 4, text: "Other", parent:null},
{id: 5, text: "Unassigned", parent:4},
{id: 6, text: "John", parent:1},
{id: 7, text: "Mike", parent:2},
{id: 8, text: "Anna", parent:2},
{id: 9, text: "Bill", parent:3},
{id: 10, text: "Floe", parent:3}
]);
Related sample: Resource load diagram
datastore.parse() дополняет gantt.parse().
Вызывает события onBeforeParse, onItemLoading, onParse и onStoreUpdated.
-
getItem (id): object | void - получает элемент по его id
- id - (string | number) - id элемента
var store = gantt.getDatastore(gantt.config.resource_store);
var resource = store.getItem(resourceId);
Related sample: Resource load diagram
datastore.getItem() соответствует gantt.getTask() и gantt.getLink().
-
updateItem (id, item): void - обновляет указанный элемент
- id - (string | number) - id элемента
- item? - (object) - объект с обновлёнными свойствами
var store = gantt.getDatastore(gantt.config.resource_store);
var resource = store.getItem(resourceId);
resource.text = "modified";
store.updateItem(resourceId);
// or
store.updateItem(resourceId, { text: "modified" });
datastore.updateItem() похож на gantt.updateTask() и gantt.updateLink().
Вызывает события onBeforeUpdate, onAfterUpdate и onStoreUpdated.
-
removeItem (id): void - удаляет указанный элемент
- id - (string | number) - id элемента
var store = gantt.getDatastore(gantt.config.resource_store);
store.removeItem(resourceId);
datastore.removeItem() аналогичен gantt.deleteTask() и gantt.deleteLink().
Вызывает события onBeforeDelete, onAfterDelete и onStoreUpdated.
-
isVisible (id): boolean - определяет, видим ли элемент или скрыт фильтрами
- id - (string | number) - id элемента
Возвращает true, если элемент видим, иначе false.
var store = gantt.getDatastore(gantt.config.resource_store);
if(store.isVisible(resourceId)){
console.log(resourceId);
}
datastore.isVisible() сравним с gantt.isTaskVisible().
-
getVisibleItems (): Array<object> - возвращает массив видимых элементов
var store = gantt.getDatastore(gantt.config.resource_store);
var items = store.getVisibleItems();
-
addItem (item, index): number | string - добавляет новый элемент в datastore
- item - (object) - объект элемента
- index? - (number) - позиция для вставки элемента (0 или больше)
Возвращает id добавленного элемента.
var store = gantt.getDatastore(gantt.config.resource_store);
var itemId = store.addItem({
text: "Unassigned",
parent:4
});
datastore.addItem() соответствует gantt.addTask() и gantt.addLink().
Вызывает события onBeforeAdd, onAfterAdd и onStoreUpdated.
-
changeId (oldId, newId): void - обновляет id элемента
- oldId - (string | number) - текущий id элемента
- newId - (string | number) - новый id для присвоения
var store = gantt.getDatastore(gantt.config.resource_store);
var itemId = store.addItem({
text: "Unassigned",
parent:4
});
// itemId — временный клиентский id для нового элемента
// обновите клиент новым id после сохранения в базе данных:
store.changeId(itemId, "databaseId");
datastore.changeId() похож на gantt.changeTaskId() и gantt.changeLinkId().
Вызывает событие onIdChange.
-
exists (id): boolean - проверяет, существует ли элемент в datastore
- id - (string | number) - id элемента
Возвращает true, если элемент существует, иначе false.
var store = gantt.getDatastore(gantt.config.resource_store);
if(store.exists(resourceId)){
console.log(resourceId);
}
datastore.exists() соответствует gantt.isTaskExists() и gantt.isLinkExists().
-
move (sindex, tindex): void - перемещает элемент на новую позицию
- sindex - (number) - текущий индекс элемента
- tindex - (number) - целевой индекс для перемещения
var store = gantt.getDatastore(gantt.config.resource_store);
// поменять местами два элемента
var idA = 1;
var idB = 5;
var indexA = store.getIndexById(idA);
var indexB = store.getIndexById(idB);
store.move(indexB, indexA);
indexA = store.getIndexById(idA);
store.move(indexA, indexB);
datastore.move() дополняет gantt.moveTask().
Вызывает событие onStoreUpdated.
-
clearAll (): void - очищает datastore
var store = gantt.getDatastore(gantt.config.resource_store);
store.clearAll();
datastore.clearAll() соответствует gantt.clearAll().
Вызывает события onClearAll, onBeforeStoreUpdate и onStoreUpdated.
-
silent (callback): void - выполняет код без вызова событий API datastore
- callback - (Function) - функция обратного вызова
var store = gantt.getDatastore(gantt.config.resource_store);
store.silent(function(){
store.eachItem(function(item){
item.text += " modified";
store.updateItem(item.id);
});
});
store.refresh();
datastore.silent() дополняет gantt.silent().
-
refresh (id): void - инициирует перерисовку событий указанной записи и применяет фильтры
- id? - (string | number) - необязательно, id записи
var store = gantt.getDatastore(gantt.config.resource_store);
store.refresh(itemId); // перерисовка конкретного элемента
store.refresh(); // перерисовка всех элементов
datastore.refresh() соответствует gantt.refreshTask() и gantt.refreshLink().
Вызывает события onBeforeStoreUpdate, onBeforeFilter, onFilterItem, onFilter и onStoreUpdated.
-
count (): number - возвращает общее количество элементов, загруженных в datastore
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onParse", function(){
alert(store.count() + " items loaded");
});
datastore.count() соответствует gantt.getTaskCount() и gantt.getLinkCount().
-
countVisible (): number - возвращает количество видимых элементов
var store = gantt.getDatastore(gantt.config.resource_store);
alert(store.countVisible() + " items are visible");
datastore.countVisible() соответствует gantt.getVisibleTaskCount().
-
eachItem (callback): void - перебирает все элементы в datastore
- callback - (Function) - функция обратного вызова
var store = gantt.getDatastore(gantt.config.resource_store);
var searchItems = [];
store.eachItem(function(item){
if(!item.value){
searchItems.push(item);
}
});
datastore.eachItem() соответствует gantt.eachTask().
-
filter (): void - применяет фильтры и обновляет список видимых элементов
Обычно этот метод вызывается автоматически через store.refresh().
var store = gantt.getDatastore(gantt.config.resource_store);
store.filter();
-
sort (field, desc, parent, silent): void - сортирует элементы в grid ресурсов
- field - (string | Function) - имя колонки для сортировки или пользовательская функция сортировки
- desc? - (boolean) - направление сортировки: true — по убыванию, false — по возрастанию (по умолчанию false)
- parent? - (string | number) - id родителя, чтобы ограничить сортировку его веткой
- silent? - (boolean) - пропустить перерисовку после сортировки
var store = gantt.getDatastore(gantt.config.resource_store);
store.parse([
{id: 1, text: "QA", parent:null},
{id: 2, text: "Development", parent:null},
{id: 3, text: "Sales", parent:null},
{id: 4, text: "Other", parent:null},
{id: 5, text: "Unassigned", parent:4},
{id: 6, text: "John", parent:1},
{id: 7, text: "Mike", parent:2},
{id: 8, text: "Anna", parent:2},
{id: 9, text: "Bill", parent:3},
{id: 10, text: "Floe", parent:3}
]);
// переключение направления сортировки по колонке
var resourceSortDirection = false;
function sortResources(){
resourceSortDirection = !resourceSortDirection;
gantt.getDatastore("resource").sort("text", resourceSortDirection)
gantt.render();
}
Или можно использовать пользовательскую функцию сортировки:
var resourceSortDirection = false;
function sortResources(){
resourceSortDirection = !resourceSortDirection;
gantt.getDatastore("resource").sort(function (resource1, resource2){
return resource1.id - resource2.id;
}, resourceSortDirection)
gantt.render();
}
datastore.sort() дополняет gantt.sort().
-
getIndexRange (from, to): Array<object> - возвращает элементы в диапазоне индексов
- from - (number) - начальная позиция
- to - (number) - конечная позиция
var store = gantt.getDatastore(gantt.config.resource_store);
var itemsInViewPort = store.getIndexRange(5, 10); // элементы с 5-го по 10-й
-
getItems (): Array<object> - возвращает все элементы в datastore
var store = gantt.getDatastore(gantt.config.resource_store);
var items = store.getItems();
datastore.getItems() соответствует gantt.getTaskByTime() и gantt.getLinks().
-
getIdByIndex (index): string | number | void - возвращает id элемента по индексу или `undefined`, если элемента нет
- index - (number) - позиция элемента
var store = gantt.getDatastore(gantt.config.resource_store);
var firstItem = store.getIdByIndex(0);
datastore.getIdByIndex() соответствует gantt.getTaskByIndex().
-
getIndexById (id): number - возвращает индекс элемента по id или `-1`, если не найден
- id - (string | number) - id элемента
var store = gantt.getDatastore(gantt.config.resource_store);
var itemIndex = store.getIndexById(5);
datastore.getIndexById() соответствует gantt.getTaskIndex().
-
getFirst (): string | number | null - возвращает id первого элемента в datastore
var store = gantt.getDatastore(gantt.config.resource_store);
var firstId = store.getFirst();
-
getLast (): string | number | null - возвращает id последнего элемента в datastore
var store = gantt.getDatastore(gantt.config.resource_store);
var lastId = store.getLast();
-
getNext (id): string | number | null - возвращает id следующего за указанным элемента
- id - (string | number) - id текущего элемента
var store = gantt.getDatastore(gantt.config.resource_store);
var firstId = store.getFirst();
var secondId = store.getNext(firstId);
datastore.getNext() соответствует gantt.getNext().
-
getPrev (id): string | number | null - возвращает id предыдущего элемента относительно указанного
- id - (string | number) - id текущего элемента
var store = gantt.getDatastore(gantt.config.resource_store);
var prevId = store.getPrev(itemId);
datastore.getPrev() соответствует gantt.getPrev().
-
destructor (): void - очищает datastore и удаляет все обработчики событий; после вызова datastore становится непригоден для использования
var store = gantt.getDatastore(gantt.config.resource_store);
store.destructor();
datastore.destructor() соответствует gantt.destructor().
-
attachEvent (name, handler, settings): string - присоединяет обработчик к внутреннему событию datastore
- name - (string) - имя события, без учёта регистра
- handler - (Function) - функция-обработчик
- settings? - (object) - необязательный объект настроек для обработчика
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onAfterSelect", function(id){
gantt.refreshData();
});
datastore.attachEvent() соответствует gantt.attachEvent().
-
callEvent (name, params): boolean - вызывает внутреннее событие
- name - (string) - имя события, без учёта регистра
- params - (Array<any>) - массив данных, связанных с событием
var store = gantt.getDatastore(gantt.config.resource_store);
store.callEvent("CustomEvent", [param1, param2]);
datastore.callEvent() соответствует gantt.callEvent().
-
detachEvent (id): void - удаляет ранее присоединённый обработчик события
- id - (string) - id обработчика события
var store = gantt.getDatastore(gantt.config.resource_store);
var handlerId = store.attachEvent("onAfterSelect", function(id){
gantt.refreshData();
});
// удаление обработчика события
store.detachEvent(handlerId);
datastore.detachEvent() соответствует gantt.detachEvent().
События
-
onItemLoading (item) - вызывается при загрузке элемента из источника данных
- item - (object) - объект элемента
Верните false, чтобы отменить стандартное поведение события, иначе true.
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onItemLoading", function(item){
if(item.valid){ // фильтрация элементов при загрузке по пользовательскому свойству
return true;
}
return false;
});
событие onItemLoading datastore соответствует событию Gantt onTaskLoading.
-
onBeforeParse (data) - вызывается перед началом парсинга данных
- data - (Array <any>) - загруженный массив данных
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeParse", function(item){
console.time("StoreParse");
});
store.attachEvent("onParse", function(item){
console.timeEnd("StoreParse");
});
событие onBeforeParse datastore соответствует событию Gantt onBeforeParse.
-
onParse (data) - вызывается после завершения парсинга, но до отрисовки в диаграмме Ганта
- data - (Array <any>) - загруженный массив данных
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeParse", function(item){
console.time("StoreParse");
});
store.attachEvent("onParse", function(item){
console.timeEnd("StoreParse");
});
событие onParse datastore соответствует событию Gantt onParse.
-
onBeforeUpdate (id, item) - вызывается перед обновлением элемента
- id - (string | number) - id элемента
- item - (object) - обновлённый объект элемента
Верните false, чтобы отменить стандартное действие события, иначе true.
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeUpdate", function(id, item){
// ваш код здесь
return true;
});
событие onBeforeUpdate datastore соответствует событиям Gantt onBeforeTaskUpdate и onBeforeLinkUpdate.
-
onAfterUpdate (id, item) - вызывается после обновления элемента
- id - (string | number) - id элемента
- item - (object) - обновлённый объект элемента
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onAfterUpdate", function(id, item){
// ваш код здесь
});
событие onAfterUpdate datastore соответствует событиям Gantt onAfterTaskUpdate и onAfterLinkUpdate.
-
onBeforeDelete (id, item) - вызывается перед удалением элемента
- id - (string | number) - id элемента
- item - (object) - объект элемента
Верните false, чтобы отменить стандартное действие события, иначе true.
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeDelete", function(id, item){
// ваш код здесь
return true;
});
событие onBeforeDelete datastore соответствует событиям Gantt onBeforeTaskDelete и onBeforeLinkDelete.
-
onAfterDelete (id, item) - вызывается после удаления элемента
- id - (string | number) - id элемента
- item - (object) - объект элемента
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onAfterDelete", function(id, item){
// ваш код здесь
});
событие onAfterDelete datastore соответствует событиям Gantt onAfterTaskDelete и onAfterLinkDelete.
-
onBeforeAdd (id, item) - вызывается перед добавлением нового элемента в datastore
- id - (string | number) - id элемента
- item - (object) - объект элемента
Верните false, чтобы отменить стандартное действие события, иначе true.
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeAdd", function(id, item){
// ваш код здесь
return true;
});
событие onBeforeAdd datastore соответствует событиям Gantt onBeforeTaskAdd и onBeforeLinkAdd.
-
onAfterAdd (id, item) - вызывается после добавления нового элемента в datastore
- id - (string | number) - id элемента
- item - (object) - объект элемента
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onAfterAdd", function(id, item){
// ваш код здесь
});
событие onAfterAdd datastore соответствует событиям Gantt onAfterTaskAdd и onAfterLinkAdd.
-
onIdChange (id, newId) - вызывается при изменении id элемента
- id - (string | number) - старый id
- newId - (string | number) - новый id
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onIdChange", function(oldId, newId){
// ваш код здесь
});
событие onIdChange datastore соответствует событию Gantt onTaskIdChange.
-
onClearAll () - вызывается после удаления всех элементов из datastore
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onClearAll", function(){
// ваш код здесь
});
событие onClearAll datastore соответствует событию Gantt onClear.
-
onBeforeStoreUpdate (id, item, action) - вызывается перед обновлением datastore
- id - (string | number | null) - id элемента или null
- item - (object | null) - объект элемента или null
- action - (string | null) - тип действия ("paint", "move", "add", "delete", null)
Верните false, чтобы отменить стандартное действие события, иначе true.
Это событие означает, что элементы datastore должны быть перерисованы. Значение `null` означает обновление всего datastore.
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeStoreUpdate", function(id, item, action){
// ваш код здесь
return true;
});
-
onStoreUpdated (id, item, action) - вызывается после обновления datastore
- id - (string | number | null) - id элемента или null
- item - (object | null) - объект элемента или null
- action - (string | null) - тип действия ("paint", "move", "add", "delete", null)
Это событие сигнализирует, что элементы datastore должны быть перерисованы. Значение `null` означает обновление всего datastore.
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onStoreUpdated", function(id, item, action){
// ваш код здесь
});
-
onBeforeFilter () - вызывается перед применением фильтров
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeFilter", function(){
console.time("filtering");
});
store.attachEvent("onFilter", function(){
console.timeEnd("filtering");
});
-
onFilter () - вызывается после применения фильтров и обновления видимых элементов
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onBeforeFilter", function(){
console.time("filtering");
});
store.attachEvent("onFilter", function(){
console.timeEnd("filtering");
});
-
onFilterItem (id, item) - вызывается для каждого элемента при фильтрации; возврат `false` скрывает элемент
- id - (string | number) - id элемента
- item - (object) - объект элемента
Верните false, чтобы скрыть элемент, иначе true.
var store = gantt.getDatastore(gantt.config.resource_store);
store.attachEvent("onFilterItem", function(id, item){
// ваш код здесь
return true;
});
событие onFilterItem datastore соответствует событию Gantt onBeforeTaskDisplay.
-
onDestroy () - вызывается после вызова метода destructor() datastore
var datastore = gantt.createDatastore({
name: gantt.config.resource_store,
type: "treeDatastore",
initItem: function (item) {
item.parent = item.parent || gantt.config.root_id;
item[gantt.config.resource_property] = item.parent;
item.open = true;
return item;
}
});
datastore.attachEvent("onDestroy", function(){
alert("free custom resources");
});
datastore.destructor();
See also
К началу