我有一个应该将数字增加一个的函数 在每个按钮上单击。该功能仅在第一次调用时正常工作,然后由于函数调用次数过多而导致数量大大增加。 有人可以解释一下发生了什么,我该如何按照与我相同的模式修复它?
'use strict';
var button = document.getElementsByClassName('button')[0],
targetElement = document.getElementsByClassName('view-box')[0];
var NumView = function NumView(element, button) {
this.element = element;
this.button = button;
};
NumView.prototype.render = function render() {
this.element.innerHTML = this.num;
this.button.addEventListener('click', changeValue.bind(this));
function changeValue() {
this.num ++;
this.render();
}
};
var NumController = function NumController(numView) {
this.numView = numView;
};
NumController.prototype.initialize = function initialize() {
this.onLoadShowNum();
};
NumController.prototype.onLoadShowNum = function onLoadShowNum() {
this.numView.num = 0;
this.numView.render();
};
(function initialize() {
var view = new NumView(targetElement, button),
controller = new NumController(view);
controller.initialize();
})();
.container {
width: 100%;
background: silver;
text-align: center;
}
.view-box {
border: 5px solid red;
padding: 5px;
background: white;
}
.button {
line-height: 2.4;
margin: 25px;
}
<section class="container">
<span class="view-box"></span>
<button class="button">Click!</button>
</section>
答案 0 :(得分:4)
每次单击按钮时都会添加一个eventListener。
就这样做。
首次创建按钮时,使用单击事件绑定按钮。
'use strict';
var button = document.getElementsByClassName('button')[0],
targetElement = document.getElementsByClassName('view-box')[0];
var NumView = function NumView(element, button) {
this.element = element;
this.button = button;
/* Place it here */
this.button.addEventListener('click', changeValue.bind(this));
function changeValue() {
this.num ++;
this.render();
}
};
NumView.prototype.render = function render() {
this.element.innerHTML = this.num;
/*Remove from here*/
/*
this.button.addEventListener('click', changeValue.bind(this));
function changeValue() {
this.num ++;
this.render();
}
//This is being called multiple times. 1 + 2 +3 +4+..
*/
};
var NumController = function NumController(numView) {
this.numView = numView;
};
NumController.prototype.initialize = function initialize() {
this.onLoadShowNum();
};
NumController.prototype.onLoadShowNum = function onLoadShowNum() {
this.numView.num = 0;
this.numView.render();
};
(function initialize() {
var view = new NumView(targetElement, button),
controller = new NumController(view);
controller.initialize();
})();
.container {
width: 100%;
background: silver;
text-align: center;
}
.view-box {
border: 5px solid red;
padding: 5px;
background: white;
}
.button {
line-height: 2.4;
margin: 25px;
}
<section class="container">
<span class="view-box"></span>
<button class="button">Click!</button>
</section>