|
常见写法
通过规律的按钮命名和传入参数不同来区分按钮,改变按钮图片
- // 定义一个长度为 10 的数组用来存取 10 个按钮的状态
- var btnStatus = new Array(10);
- // 每个按钮点击时执行 这个方法, 通过传入参数 0~9 来标识是哪个按钮
- // 这写按钮的名字也命名成有规律,前缀相同只有最后一位不相同为 0~9 数字
- function btnClick(id) {
- if (btnStatus[id] == 1) {
- btnStatus[id] = 0;
- setButtonImage("按钮名称前缀"+id,"OFF状态图片.png");
- // OFF 状态时 发送代码或者其他操作
- // 可以通过 id 来区分按钮
- // sendCodeString("COM1",id); // 发送代码
- } else {
- btnStatus[id] = 1;
- setButtonImage("按钮名称前缀"+id,"ON状态图片.png");
- // ON 状态时候
- }
- }
复制代码
构造函数方法
通过构造函数的方式,只需要传入按钮名称,实例化过程中根据按钮名称获取按钮的on、off图片
改变状态时同时改变图片
update方法用于更新按钮图片,如APP退出时,可在进入页面时刷新按钮状态
也可以再封装一层,实现多个按钮的状态管理
- function clickToggle(name, status) {
- this.name = name;
- this.imageOn = getImageOn(name);
- this.imageOff = getImageOff(name);
- this.status = status || 0;
- this.onArr = [];
- this.offArr = [];
- this.click = function () {
- if (this.status) {
- setButtonImage(this.name, this.imageOff);
- this.status = 0;
- this.emit("off");
- } else {
- setButtonImage(this.name, this.imageOn);
- this.status = 1;
- this.emit("on");
- }
- }
- this.on = function () {
- setButtonImage(this.name, this.imageOn);
- this.status = 1;
- this.emit("on");
- }
- this.off = function () {
- setButtonImage(this.name, this.imageOff);
- this.status = 0;
- this.emit("off");
- }
- this.update = function () {
- if (this.status) {
- setButtonImage(this.name, this.imageOn);
- } else {
- setButtonImage(this.name, this.imageOff);
- }
- }
- this.subscribe = function (action, cb) {
- if (typeof cb != 'function') {
- throw "clickToggle " + this.name + " subscribe 参数2错误,应该传入回调函数";
- }
- if (action.toLowerCase() == "on") {
- this.onArr.push(cb);
- }
- if (action.toLowerCase() == "off") {
- this.offArr.push(cb);
- }
- }
- this.emit = function (action) {
- var array = [];
- if (action.toLowerCase() == "on") {
- array = this.onArr;
- }
- if (action.toLowerCase() == "off") {
- array = this.offArr;
- }
- for (var i = 0; i < array.length; i++) {
- var element = array[i];
- try {
- element();
- } catch (error) {
- sendLog("clickToggle " + this.name, error)
- }
- }
- }
- }
- // clickToggle 实例化可以传入两个参数,也可以只传按钮名称
- // 参数1 按钮名称
- // 参数2 按钮的初始状态 0 为 off 1 为on
- var bt1 = new clickToggle("test", 1);
- // var bt1 = new clickToggle("test");
- // 更新按钮状态 实例化以后可以在任何时候更新状态
- // 会根据按钮状态重新改变按钮图片
- bt1.update();
- // 订阅 按钮的 on off 点击事件
- bt1.subscribe("on", function () {
- // 按钮被点击且状态为 on 时执行
- sendLog("按钮被点击了", "状态为 ON");
- })
- // 订阅 按钮的 on off 点击事件
- // 参数1 为订阅事件 只能为 on 或者 off
- // 参数2 为回调函数
- bt1.subscribe("off", function () {
- // 按钮被点击且状态为 off 时执行
- sendLog("按钮被点击了", "状态为 OFF");
- })
- function buttonOffStatus() {
- // 按钮被点击且状态为 off 时执行
- sendLog("按钮被点击了", "状态为 OFF");
- }
- // 另一种写法
- // on off 状态上可以多次订阅
- // 状态变化时依次执行
- bt1.subscribe("off",buttonOffStatus);
- // 按钮的点击
- // 当前状态为 on 时 点击后 按钮将变成 off 状态
- // 当前状态为 off 时 点击后 按钮将变成 on 状态
- bt1.click();
- // 设置按钮状态 不管按钮处于什么状态使之处于 on 状态
- bt1.on();
- // 设置按钮状态 不管按钮处于什么状态使之处于 off 状态
- bt1.off();
复制代码
|
|