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 16type SongItem = { 17 id: number, 18 title: string, 19 singer: string, 20 label: Resource 21} 22 23export default class MyDataSource implements IDataSource { 24 private dataArray: SongItem[] = [] 25 private listeners: DataChangeListener[] = [] 26 27 constructor(element: SongItem[]) { 28 for (let index = 0; index < element.length; index++) { 29 this.dataArray.push(element[index]) 30 } 31 } 32 33 public totalCount(): number { 34 return this.dataArray.length 35 } 36 37 public getData(index: number): SongItem { 38 return this.dataArray[index] 39 } 40 41 public addData(index: number, data: SongItem): void { 42 this.dataArray.splice(index, 0, data) 43 this.notifyDataAdd(index) 44 } 45 46 public pushData(data: SongItem): void { 47 this.dataArray.push(data) 48 this.notifyDataAdd(this.dataArray.length - 1) 49 } 50 51 registerDataChangeListener(listener: DataChangeListener): void { 52 if (this.listeners.indexOf(listener) < 0) { 53 console.info('add listener') 54 this.listeners.push(listener) 55 } 56 } 57 58 unregisterDataChangeListener(listener: DataChangeListener): void { 59 const pos = this.listeners.indexOf(listener); 60 if (pos >= 0) { 61 console.info('remove listener') 62 this.listeners.splice(pos, 1) 63 } 64 } 65 66 notifyDataReload(): void { 67 this.listeners.forEach(listener => { 68 listener.onDataReloaded() 69 }) 70 } 71 72 notifyDataAdd(index: number): void { 73 this.listeners.forEach(listener => { 74 listener.onDataAdd(index) 75 }) 76 } 77 78 notifyDataChange(index: number): void { 79 this.listeners.forEach(listener => { 80 listener.onDataChange(index) 81 }) 82 } 83 84 notifyDataDelete(index: number): void { 85 this.listeners.forEach(listener => { 86 listener.onDataDelete(index) 87 }) 88 } 89 90 notifyDataMove(from: number, to: number): void { 91 this.listeners.forEach(listener => { 92 listener.onDataMove(from, to) 93 }) 94 } 95}