cocos 组件扩展封装

扩展按钮类
跨页面传参通信 onfire下载

/**
 * 扩展按钮类
 * @type {Function|*}
 */
cc.bsButton = cc.Class({
    extends: cc.Component,
    editor: {
        requireComponent: cc.Button
    },

    ctor: function () {
        this.onClicks = cc.bsList();            //  点击事件容器
    },

    properties: {
        //  是否标准化
        isNormal: true,

        //  点击音效
        clickAudio: {
            default: null,
            type: cc.AudioClip
        }
    },

    init: function () {
        //  标准化处理
        if (this.isNormal) {
            this.btn.transition = cc.Button.Transition.SCALE;
            this.btn.zoomScale = 1.05;
        }
    },

    onLoad: function () {
        this.btn = this.node.getComponent(cc.Button);
        //  监听触摸事件
        this.node.on(cc.Node.EventType.TOUCH_START, event => {
        }, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, event => {
        }, this);
        this.node.on(cc.Node.EventType.TOUCH_END, event => {
            //  处理点击事件
            // let url = this.clickAudio;
            // if (url) cc.audioEngine.play(url, false, 1);
            cc.globalValue.playMusic("btnsfx_1",false,0.5);
            if(!this.btn.interactable){                
                return;
            }             
            this.onClicks.each(listener => {
                listener.call(listener.context, event);
            });
        }, this);
        this.init();
    },

    onDisable: function () {
        //  重置按钮状态
        if(this.btn)
            this.btn._transitionFinished = true;
        this.node.setScale(1, 1);
    },

    onDestroy: function () {
        this.node.targetOff(this);
        this.removeAllClickListener();
    },

    /**
     * 添加点击事件
     * @param callback
     * @param context
     * @returns {cc.bsButton}
     */
    addClickListener: function (callback, context) {
        if (!callback)
            return this;

        callback.context = context || this;
        this.onClicks.append(callback);

        return this;
    },

    /**
     * 移除点击事件
     * @param callback
     * @returns {cc.bsButton}
     */
    removeClickListener: function (callback) {
        this.onClicks.remove(callback);

        return this;
    },

    /**
     * 清空所有点击事件
     */
    removeAllClickListener: function () {
        this.onClicks.clear();
    },

});

你可能感兴趣的:(cocos 组件扩展封装)