cocos creator-2.3.4-使用schedule回调函数,实现一个倒计时功能

废话不多说,先上代码:

const {ccclass, property} = cc._decorator;

@ccclass
export default class Countdown extends cc.Component {

    @property(cc.Animation)
    animation: cc.Animation = null;

    @property(cc.Label)
    labelComponent: cc.Label = null;

    count: number = 0;
    callback: Function = null;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {}

    start () {}

    showTime (time: number) {
        this.count = time;
        this.animation.play();

        this.callback = function () {
            if (this.count <= 0) {
                this.labelComponent.unschedule(this.callback);
                return;
            }
            this.count--;
            **this.labelComponent.string = this.count.toString();**  // 访问组件需绑定响应函数调用者为this
        }.bind(this)
        this.labelComponent.schedule(this.callback, 1);
        this.labelComponent.string = this.count.toString();

    }

    // update (dt) {}
}

问题出在这句:this.labelComponent.string = this.count.toString(); ,如果想在this.callback 中设置 this.labelComponent.string,正确的用法是 this.callback = funtion () {}.bind(this),否则会报这样的错误:Uncaught TypeError: Cannot set property 'string' of undefined

creator官方文档-计时器的使用
creator官方文档-bind绑定响应函数的调用者

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容