gpt4 book ai didi

javascript - ES6 中的 Backbone 事件

转载 作者:行者123 更新时间:2023-11-30 11:28:12 25 4
gpt4 key购买 nike

我使用 ES5 形式的 Backbone 已经有一段时间了,我希望尝试在 ES6 中构建一个新项目。我构建了这个非常基本的 View 只是为了测试我的构建过程等。

我可以让 View 在 el 中按预期呈现。但是,我似乎根本无法触发该事件。我确信我遗漏了一些简单的东西,但我似乎找不到它是什么。

import $ from "jquery";
import _ from 'underscore';
import Backbone from 'backbone';

class basicView extends Backbone.View {
constructor(options) {
super();
this.options = options;
this.events = {
'click #bc': 'clickHandler'
};
this.render();
}

render() {
$(this.options.el).html('<a id="bc" href="#">button</a>');
return this;
}

clickHandler() {
alert("button clicked");
return false;
}
};

$(() => {
new basicView({
el: '#container'
});
});
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>es6</title>

</head>

<body>
<div id="container">

</div>
<script src="ui/js/production/home.js"></script>
</body>

</html>

最佳答案

正如您在构造函数中看到的那样,您在 调用 Backbone.View 的代码后定义了 events,该代码执行解析事件哈希和绑定(bind)事件等操作。

constructor(options) {
super();
// ^---- don't have an event hash when this code executes.
this.events = { // this is now useless
'click #bc': 'clickHandler'
};

super(options) 并在 options 中传递事件散列可能会起作用。简单而优雅的解决方案:使用 Backbone.View.extend() 而不是 class。通过将 class 与 backbone 一起使用,您除了缺点之外什么也得不到。您仍然可以在项目中使用所有其他 ES6 功能。

关于javascript - ES6 中的 Backbone 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47212754/

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