Skip to content

Instantly share code, notes, and snippets.

@alsotang
Last active October 23, 2023 02:41
Show Gist options
  • Save alsotang/3eea2ccee640389ff7e604cf8006d49e to your computer and use it in GitHub Desktop.
Save alsotang/3eea2ccee640389ff7e604cf8006d49e to your computer and use it in GitHub Desktop.
在 cocos creator 中实现数据绑定视图
import { _decorator, Component } from 'cc'
const { ccclass, property } = _decorator;
/** 浅对比是否相同 */
function isShallowEqual(value: Record<string, any>, other: Record<string, any>) {
if (value === other) {
return true
}
if (!value || !other) {
return false
}
const valueKeys = Object.keys(value)
const otherKeys = Object.keys(other)
if (valueKeys.length !== otherKeys.length) {
return false
}
for (let i = 0; i < valueKeys.length; i++) {
const key = valueKeys[i]
if (!Object.prototype.hasOwnProperty.call(other, key) || value[key] !== other[key]) {
return false
}
}
return true
}
@ccclass('DirtyCheckComponent')
export abstract class DirtyCheckComponent extends Component {
abstract deps: Record<string, any>
/** 依赖是否变化。 */
isDepsChanged: boolean = false
start() {
}
/** 由子类实现 */
abstract getDeps(): typeof this.deps;
/** 子类需要调用 super.update,然后判断 isDepsChanged 如果为 true,则从 deps 里面取数据来更新ui。 */
update(deltaTime: number) {
const deps = this.getDeps()
if (!isShallowEqual(deps, this.deps)) {
this.isDepsChanged = true
this.deps = deps
} else {
this.isDepsChanged = false;
}
}
}
@ccclass('LeafComponent')
export class LeafComponent extends DirtyCheckComponent {
deps = {
isEnableNextLevel: false,
}
start() {
}
update(deltaTime: number) {
super.update(deltaTime);
if (this.isDepsChanged) {
this.doSomeUiUpdate(this.deps.isEnableNextLevel);
}
}
getDeps(): typeof this.deps {
return {
isEnableNextLevel: globalInstances.gameManager.isEnableNextLevel,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment