1/** 2 * Copyright (c) 2021-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 16import commonEvent from '@ohos.commonEvent'; 17import {Log, dateTimeCommon, sTimeManager, TimeEventArgs, TIME_CHANGE_EVENT, sEventManager, unsubscribe} from '@ohos/common' 18 19const TAG = 'ScreenLock-DateTimeViewModel' 20 21let mCommonEventSubscribeInfo = { 22 events: [ 23 commonEvent.Support.COMMON_EVENT_TIME_CHANGED, 24 commonEvent.Support.COMMON_EVENT_TIMEZONE_CHANGED, 25 commonEvent.Support.COMMON_EVENT_TIME_TICK 26 ] 27}; 28 29let mEventSubscriber 30 31/** 32 * DateTimeViewModel class 33 */ 34export default class DateTimeViewModel { 35 timeVal: string = '' 36 dateVal: any = {} 37 weekVal: any = {} 38 calendarVal: any = {} 39 unSubscriber?: unsubscribe; 40 41 ViewModelInit(): void{ 42 Log.showDebug(TAG, 'ViewModelInit'); 43 44 this.getAndSetDateTime.bind(this)() 45 commonEvent.createSubscriber(mCommonEventSubscribeInfo, this.createSubscriberCallBack.bind(this)); 46 this.unSubscriber = sEventManager.subscribe(TIME_CHANGE_EVENT, (args: TimeEventArgs) => { 47 this.setDateTime(args.date) 48 }); 49 Log.showDebug(TAG, 'ViewModelInit end'); 50 } 51 52 private getAndSetDateTime() { 53 Log.showDebug(TAG, `getAndSetDateTime`) 54 this.setDateTime(new Date()) 55 } 56 57 private setDateTime(date: Date) { 58 Log.showDebug(TAG, `setDateTime`) 59 this.timeVal = sTimeManager.formatTime(date) 60 this.dateVal = dateTimeCommon.getSystemDate() 61 this.weekVal = dateTimeCommon.getSystemWeek() 62 this.calendarVal = dateTimeCommon.getCalendarDate() 63 } 64 65 private createSubscriberCallBack(err, data) { 66 Log.showDebug(TAG, "start createSubscriberCallBack " + JSON.stringify(data)) 67 mEventSubscriber = data 68 commonEvent.subscribe(data, this.getAndSetDateTime.bind(this)); 69 Log.showDebug(TAG, "start createSubscriberCallBack finish") 70 } 71 72 stopPolling() { 73 Log.showDebug(TAG, `stopPolling start`) 74 commonEvent.unsubscribe(mEventSubscriber); 75 this.unSubscriber && this.unSubscriber(); 76 this.unSubscriber = undefined; 77 Log.showDebug(TAG, `stopPolling end`) 78 } 79} 80