1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16class BasicDataSource implements IDataSource { 17 private listeners: DataChangeListener[] = [] 18 19 public totalCount(): number { 20 return 0 21 } 22 23 public getData(index: number): any { 24 return undefined 25 } 26 27 registerDataChangeListener(listener: DataChangeListener): void { 28 if (this.listeners.indexOf(listener) < 0) { 29 console.info('add listener') 30 this.listeners.push(listener) 31 } 32 } 33 34 unregisterDataChangeListener(listener: DataChangeListener): void { 35 const pos = this.listeners.indexOf(listener); 36 if (pos >= 0) { 37 console.info('remove listener') 38 this.listeners.splice(pos, 1) 39 } 40 } 41 42 notifyDataReload(): void { 43 this.listeners.forEach(listener => { 44 listener.onDataReloaded() 45 }) 46 } 47 48 notifyDataAdd(index: number): void { 49 this.listeners.forEach(listener => { 50 listener.onDataAdd(index) 51 }) 52 } 53 54 notifyDataChange(index: number): void { 55 this.listeners.forEach(listener => { 56 listener.onDataChange(index) 57 }) 58 } 59 60 notifyDataDelete(index: number): void { 61 this.listeners.forEach(listener => { 62 listener.onDataDelete(index) 63 }) 64 } 65 66 notifyDataMove(from: number, to: number): void { 67 this.listeners.forEach(listener => { 68 listener.onDataMove(from, to) 69 }) 70 } 71} 72 73export class MyDataSource extends BasicDataSource { 74 private dataArray: any[] = [] 75 76 constructor(data: any[]) { 77 super() 78 this.dataArray = data 79 } 80 81 public totalCount(): number { 82 return this.dataArray.length 83 } 84 85 public getData(index: number): any { 86 return this.dataArray[index] 87 } 88 89 public addData(index: number, data: any): void { 90 this.dataArray.splice(index, 0, data) 91 this.notifyDataAdd(index) 92 } 93 94 public pushData(data: any): void { 95 this.dataArray.push(data) 96 this.notifyDataAdd(this.dataArray.length - 1) 97 } 98}