有这样一个需求:没有代码不太好描述啊,js闭包内的构造函数因为业务需要new两次,而构造函数内有绑定事件,导致事件触发两次的情况。不明白?先看下代码吧...最下边有测试地址哦
前端技术:
Semantic UI/jQuery
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="测试闭包">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/semantic-ui/2.2.13/semantic.min.css">
</head>
<body>
<div class="ui top attached tabular menu">
<a class="active item" data-tab="first">First</a>
<a class="item" data-tab="second">Second</a>
</div>
<div class="ui bottom attached active tab segment" data-tab="first">
<button class="ui positive basic button">click it</button>
</div>
<div class="ui bottom attached tab segment" data-tab="second">
<button class="ui positive basic button">click it</button>
</div>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<script src="https://cdn.bootcss.com/semantic-ui/2.2.13/semantic.min.js"></script>
</body>
</html>
JS:
// Semantic UI 初始化
$('.menu .item').tab();
document.onload = (function() {
"use strict";
var GraphCreator = function(clickable) {
var thisGraph = this;
thisGraph.state = {
clickable: clickable,
clicked: false,
}
$('button').on('click', function() {
alert('触发click!');
var state = thisGraph.state;
if (state.clickable && !state.clicked) {
state.clicked = true;
alert('点击以后clicked属性修改!');
}
})
}
/**** MAIN ****/
var graph = new GraphCreator(true);
var graph_active;
$('.menu>[data-tab=second]').on('click', function() {
if (!graph_active) {
graph_active = new GraphCreator(true);
}
})
})()
看一下JS代码,GraphCreator
构造函数内部,button事件因为用到了构造函数内部的很多数据,无法放在构造函数之外。 /**** MAIN ****/
下第一次加载时创建对象graph,当点击second标签页时,此标签下的元素需要有相同的功能,创建第二个对象graph_active,从而导致点击button时会触发两次事件。有没有办法,防止触发两次事件。
操作如下:
测试地址:Demo Online
真正项目里边数据结构要远远比此Demo要复杂。求帮助啊...
我感觉单单凭一个小Demo不能说明我的问题,看一下我的项目演示吧,debug的地方就相当于此Demo中的button事件,点编辑的时候会产生一个新标签页同时new一个graph实例,所以每次都会触发两次...产生的‘块活动’和‘过程’两个标签下要有相同的功能(包括拖拽、右击菜单等)才选择再实例化一次
你这个就是点击事件里面有点击事件,