我试图使用MVC方法创建一个简单的计数器应用程序,我还没能弄清楚为什么事件侦听器的下行计数器不工作,但上行计数器。我肯定忽略了什么,但我对这种方法完全陌生。任何帮助都将非常感激。
//model
var model =
{
clickCount: 0
};
//controller
var controller = {
init: function() {
view.init();
},
incrementCounterUp: function() {
counter.textContent = model.clickCount += 1;
},
incrementCounterDown: function() {
counter.textContent = model.clickCount -= 1;
}
};
//view
var counter = document.createElement('p');
counter.textContent = (model.clickCount);
counter.id = counter;
document.body.appendChild(counter);
var upButton = document.createElement("button");
upButton.id = upButton;
document.body.appendChild(upButton);
var upButtonText = document.createTextNode("Up");
upButtonText.id = upButtonText;
upButton.appendChild(upButtonText);
var downButton = document.createElement("button");
downButton.id = downButton;
document.body.appendChild(downButton);
var downButtonText = document.createTextNode("Down");
downButtonText.id = downButtonText;
downButton.appendChild(downButtonText);
var view = {
init: function() {
// store pointers to our DOM elements for easy access
this.counterElem = document.getElementById(counter);
this.upButtonElem = document.getElementById(upButton);
this.upButtonElem.addEventListener('click', function(){
controller.incrementCounterUp();
});
this.downButtonElem = document.getElementById(downButton);
this.downButtonElem.addEventListener('click', function(){
controller.incrementCounterDown();
});
}
};
controller.init();
contoller.incrementCounterDown();
你拼错了controller。: P
//model
var model =
{
clickCount: 0
};
//controller
var controller = {
init: function() {
view.init();
},
incrementCounterUp: function() {
model.clickCount += 1
view.render()
},
incrementCounterDown: function() {
model.clickCount -= 1
view.render()
}
};
//view
var counter = document.createElement('p');
counter.textContent = (model.clickCount);
counter.id = 'counter';
document.body.appendChild(counter);
var upButton = document.createElement("button");
upButton.textContent = 'Up'
upButton.id = 'upButton';
document.body.appendChild(upButton);
var downButton = document.createElement("button");
downButton.textContent = 'Down';
downButton.id = 'downButton';
document.body.appendChild(downButton);
var view = {
init: function() {
// store pointers to our DOM elements for easy access
this.upButtonElem = document.getElementById('upButton')
this.downButtonElem = document.getElementById('downButton')
this.downButtonElem.addEventListener('click', function(){
controller.incrementCounterDown()
})
this.upButtonElem.addEventListener('click', function(){
controller.incrementCounterUp()
})
},
render: function() {
this.counterElem = document.getElementById('counter')
this.counterElem.textContent = model.clickCount
}
};
controller.init();