【发布时间】:2021-11-25 23:14:07
【问题描述】:
我正在尝试在一个简单的 print hello world 程序中实现模型视图控制器模式。在我单击程序中的按钮后,我可以让一切正常工作,除了最后。我正在尝试将我的函数绑定到控制器,以便函数使用控制器中的 this 语句来访问控制器中的模型和视图实例。当我单击按钮时,我的函数中的 this 语句正在引用我的按钮对象而不是控制器。我无法使用 bind 更改 this 语句指向的内容。请,任何帮助将不胜感激。谢谢。
<!DOCTYPE html>
<html lang="en">
<head>
<title> Hello World MVC </title>
<link rel="stylesheet" href="css file name">
</head>
<body>
<div id="container">
<input type=text id="textBox">
<button id="displayButton">Display</button>
</div>
<script src="mainbind.js"></script>
</body>
</html>
function Model(text) {
this.data = text;
};
function View() {
this.displayButton = document.getElementById('displayButton');
this.textBox = document.getElementById('textBox');
this.initialize = function(displayButtonProcess) {
this.displayButton.addEventListener('click', displayButtonProcess);
}
};
function Controller(text) {
this.model = new Model(text);
this.view = new View;
this.buttonClick = function(event) {
// process the button click event
this.view.textBox.value = this.model.data;
};
this.view.initialize(this.buttonClick);
};
let x = new Controller("Hello World");
x.buttonClick = x.buttonClick.bind(x);
【问题讨论】:
标签: javascript html css model-view-controller this