Cocos Creator 记录七-全局变量

全局变量

由于所有插件脚本都保证了会在普通脚本之前加载,那么除了用来加载插件,你还可以利用这个特性声明一些特殊的全局变量。你可以在项目中添加这样一个脚本,并且设置“导入为插件”:

/* globals.js */

// 定义新建组件的默认值
window.DEFAULT_IP = "192.168.1.1";

// 定义组件开关
window.ENABLE_NET_DEBUGGER = true;

// 定义引擎 API 缩写(仅适用于构造函数)
window.V2 = cc.Vec2;
接下来你就能在任意的普通脚本中直接访问它们:

/* network.js */

cc.Class({
    extends: cc.Component,
    properties: {
        ip: {
            default: DEFAULT_IP
        }
    }
});
/* network_debugger.js */

if (ENABLE_NET_DEBUGGER) {
    // ENABLE_NET_DEBUGGER 时这个组件才生效
    cc.Class({
        extends: cc.Component,
        properties: {
            location: {
                default: new V2(100, 200)
            }
        },
        update: function () {
            ...
        },
    });
}
else {
    // 否则这个组件什么也不做
    cc.Class({
        extends: cc.Component,
        start: function () {
            // 在开始后就移除该组件
            this.destroy();
        }
    });
}

标准网络接口

在 Cocos Creator 中,我们支持 Web 平台上最广泛使用的标准网络接口:

XMLHttpRequest:用于短连接
WebSocket:用于长连接
当然,在 Web 平台,浏览器原生就支持这两个接口,之所以说 Cocos Creator 支持,是因为在发布原生版本时,用户使用这两个网络接口的代码也是可以运行的。也就是遵循 Cocos 一直秉承的 “一套代码,多平台运行” 原则。

使用方法

XMLHttpRequest 简单示例:

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function () {
     if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
         var response = xhr.responseText;
         console.log(response);
     }
 };
 xhr.open("GET", url, true);
 xhr.send();

开发者可以直接使用 new XMLHttpRequest() 来创建一个连接对象,也可以通过 cc.loader.getXMLHttpRequest() 来创建,两者效果一致。

XMLHttpRequest 的标准文档请参考 MDN 中文文档

WebSocket

简单示例:

 ws = new WebSocket("ws://echo.websocket.org");
 ws.onopen = function (event) {
     console.log("Send Text WS was opened.");
 };
 ws.onmessage = function (event) {
     console.log("response text msg: " + event.data);
 };
 ws.onerror = function (event) {
     console.log("Send Text fired an error");
 };
 ws.onclose = function (event) {
     console.log("WebSocket instance closed.");
 };

 setTimeout(function () {
     if (ws.readyState === WebSocket.OPEN) {
         ws.send("Hello WebSocket, I'm a text message.");
     }
     else {
         console.log("WebSocket instance wasn't ready...");
     }
 }, 3);

WebSocket 的标准文档请参考 MDN 中文文档

猜你喜欢

转载自blog.csdn.net/zhengjuqiang/article/details/80843024