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() { 20 return 0 21 } 22 23 public getData(index: number) { 24 return undefined 25 } 26 27 registerDataChangeListener(listener: DataChangeListener) { 28 if (this.listeners.indexOf(listener) < 0) { 29 this.listeners.push(listener) 30 } 31 } 32 33 unregisterDataChangeListener(listener: DataChangeListener) { 34 const pos = this.listeners.indexOf(listener) 35 if (pos >= 0) { 36 this.listeners.splice(pos, 1) 37 } 38 } 39 40 notifyDataReload() { 41 this.listeners.forEach(listener => { 42 listener.onDataReloaded() 43 }) 44 } 45 46 notifyDataAdd(index: number) { 47 this.listeners.forEach(listener => { 48 listener.onDataAdd(index) 49 }) 50 } 51 52 notifyDataChange(index: number) { 53 this.listeners.forEach(listener => { 54 listener.onDataChange(index) 55 }) 56 } 57 58 notifyDataDelete(index: number) { 59 this.listeners.forEach(listener => { 60 listener.onDataDelete(index) 61 }) 62 } 63 64 notifyDataMove(from: number, to: number) { 65 this.listeners.forEach(listener => { 66 listener.onDataMove(from, to) 67 }) 68 } 69} 70 71export class MyDataSource extends BasicDataSource { 72 private dataArray: any[] = [] 73 74 constructor(dataArray: any[]){ 75 super() 76 this.dataArray = dataArray 77 } 78 79 public totalCount() { 80 return this.dataArray.length 81 } 82 83 public getData(index: number) { 84 return this.dataArray[index] 85 } 86 87 public addData(index: number) { 88 this.dataArray.splice(index, 0) 89 this.notifyDataAdd(index) 90 } 91 92 public pushData(index: number) { 93 this.dataArray.push(index) 94 this.notifyDataAdd(this.dataArray.length - 1) 95 } 96 97 public replaceData(result: any[]) { 98 this.dataArray = result 99 this.notifyDataReload() 100 } 101}