zoukankan      html  css  js  c++  java
  • Cocos Creator 为Button添加事件的两种方法

    Button添加事件

    Button 目前只支持 Click 事件,即当用户点击并释放 Button 时才会触发相应的回调函数。
    通过脚本代码添加回调
    方法一
    这种方法添加的事件回调和使用编辑器添加的事件回调是一样的,通过代码添加, 你需要首先构造一个 cc.Component.EventHandler 对象,然后设置好对应的 target, component, handler 和 customEventData 参数。
    //here is your component file, file name = MyComponent.js 
    cc.Class({
    extends: cc.Component,
    properties: {},

    onLoad: function () {
        var clickEventHandler = new cc.Component.EventHandler();
        clickEventHandler.target = this.node; //这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = "MyComponent";//这个是代码文件名
        clickEventHandler.handler = "callback";
        clickEventHandler.customEventData = "foobar";
    
        var button = node.getComponent(cc.Button);
        button.clickEvents.push(clickEventHandler);
    },
    
    callback: function (event, customEventData) {
        //这里 event 是一个 Touch Event 对象,你可以通过 event.target 取到事件的发送节点
        var node = event.target;
        var button = node.getComponent(cc.Button);
        //这里的 customEventData 参数就等于你之前设置的 "foobar"
    }

    });

    方法二
    通过 button.node.on('click', ...) 的方式来添加,这是一种非常简便的方式,但是该方式有一定的局限性,在事件回调里面无法 获得当前点击按钮的屏幕坐标点。
    //假设我们在一个组件的 onLoad 方法里面添加事件处理回调,在 callback 函数中进行事件处理:
    cc.Class({
    extends: cc.Component,
    properties: {
    button: cc.Button
    },

    onLoad: function () {
       this.button.node.on('click', this.callback, this);
    },
    
    callback: function (event) {
       //这里的 event 是一个 EventCustom 对象,你可以通过 event.detail 获取 Button 组件
       var button = event.detail;
       //do whatever you want with button
       //另外,注意这种方式注册的事件,也无法传递 customEventData
    }

    });

  • 相关阅读:
    Linux 安装apache2时候遇到的问题
    ubuntu安装php时出现error: xml2config not found. Please check your libxml2 installation 的解决办法
    Linux一块网卡绑定2个IP地址
    php 满足条件后跳转的几种方法.
    Linux 安装php 遇到 libtool: link: `ext/date/php_date.lo' is not a valid libtool object
    js 光标移动到输入框最后位置函数
    Linux iptables 防火墙相关命令介绍及使用
    tcpdump的简单选项介绍
    子网掩码转换函数
    Linux 十六进制转换十进制的函数
  • 原文地址:https://www.cnblogs.com/luorende/p/8150415.html
Copyright © 2011-2022 走看看