gpt4 book ai didi

javascript - 当 View 被注入(inject)到 Controller 中时,如何从我的 View 类中获取事件监听器以引用 Controller 类中的方法?

转载 作者:行者123 更新时间:2023-11-30 19:53:27 27 4
gpt4 key购买 nike

我不知道如何让 View 中的事件监听器引用 Controller 中的方法。我想在 View 中分配我的所有监听器,但这是在构造函数中执行此操作的方法吗?

如何将监听器绑定(bind)到 Controller 中的方法?

class Model {
constructor(test) {
this.test = test;
}
}

class View {
constructor(element) {
this.element = element;
element.addEventListener('dragenter', dragEnter, false);
element.addEventListener('drop', drop, false);
}
}

class Controller {
constructor(penguinView, penguinModel) {
this.penguinView = penguinView;
this.penguinModel = penguinModel;
}

dragEnter(e) {
console.log('enter');
}

drop(e) {
console.log('drop');
}
}

function ready() {
const penguinModel = new Model();

const targetElement = document.getElementById('listOfPenguins');
const penguinView = new View(targetElement);

const controller = new Controller(penguinView, penguinModel);

function preventDefault(e) {
e.preventDefault();
}
window.addEventListener('dragleave', preventDefault, false);
window.addEventListener('dragover', preventDefault, false);
window.addEventListener('drop', preventDefault, false);
}

document.addEventListener('DOMContentLoaded', ready);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>App</title>
</head>

<body>
<div id="listOfPenguins" class="list-of-penguins"></div>
</body>

</html>

最佳答案

通常,开发人员习惯遵循事件驱动架构,您可以在其中触发事件并附加监听器。

让我们编写一个基础 EventEmitter 类:

class EventEmitter {
constructor() {
this._events = {};
}

trigger(eventName, eventData) {
var handlers = this._events[eventName];
if (handlers) {
handlers.forEach(handler => handler.call(this, eventData));
}
return this;
}

on(eventName, eventHandler) {
this._events[eventName] = this._events[eventName] || [];
this._events[eventName].push(eventHandler);
return this;
}
}

EventEmitter 扩展 View:

class View extends EventEmitter{
constructor(element) {
super();
this.element = element;

element.addEventListener('dragenter', (evt) => this.trigger('dragenter', evt), false);
element.addEventListener('drop', (evt) => this.trigger('drop', evt), false);
}
}

ControllerView 实例上绑定(bind)事件:

class Controller {
constructor(penguinView, penguinModel) {
this.penguinView = penguinView;
this.penguinModel = penguinModel;

this.penguinView
.on('dragenter', this.dragEnter)
.on('drop', this.drop);
}

dragEnter(e) {
console.log('enter');
}

drop(e) {
console.log('drop');
}
}

关于javascript - 当 View 被注入(inject)到 Controller 中时,如何从我的 View 类中获取事件监听器以引用 Controller 类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com