如何绑定'this'点击监听器并使用事件 - es6



我有一个多步骤形式,有 4 个框架集。当我按下"下一步"按钮时,每个人都必须进来(当然(

我的 ES6 模块化代码是这样的:

class FormController {
// 1. describe and initiate object
constructor() {
this.nextBtn = $(".next");
this.next_fs;
.... 
this.events();
}
// EVENTS LISTENER
events(){
this.nextBtn.on("click", this.nextClicked.bind(this));
// other listeners
}
nextClicked() {
this.next_fs = $(this)
.parent()
.next(); // this is the next fieldset
// some actions...
}
// rest of the code
}

我的问题如下: 我需要在函数nextClicked绑定"this"才能使用所有变量和方法,如this.next_fsthis.saveData()等......

但是我还需要知道点击了哪个按钮,我无法知道,因为this不再是"这个按钮",而且我不能传递一个变量(我们称之为'e'(来跟踪e.target。

我的代码是怎么回事?我知道这是我没有看到的愚蠢的东西。

谢谢!

但我还需要知道点击了哪个按钮,我无法知道,因为"this"不再是"this button",我不能传递一个变量(我们称之为'e'(来跟踪e.target。

浏览器的事件触发代码传递该代码。你只需要阅读它。

nextClicked(e) {

"...而且我无法传递一个变量(我们称之为'e'(来跟踪 e.target">

实际上,您不需要将其作为变量传递,因为即使您不传递e也可以nextClicked获取它,因为浏览器默认这样做,因此如果您将函数声明为nextClicked(e){...}并保持绑定,它将作为参数出现。

或者,您可以在this之后传递参数,例如...bind(this, this.nextBtn),则nextCliked上的第一个参数将是按钮。

请参阅下面我提到的这两种可能性:

$(".buttons").on("click", this.nextClicked.bind(this))
function nextClicked(e){
//here your context is the same as when you binded the function, but you have the event
let target = e.target;
console.log(target.id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn-1" class="buttons">click me 1</button>
<button id="btn-2" class="buttons">click me 2</button>

let nextButton = $("#btn-1")[0];
$(".buttons").on("click", this.nextClicked.bind(this, nextButton))
function nextClicked(nextBtn, e) {
//here your context is the same as when you binded the function,
//but you have the button AND the event
console.log("NextButton Id: " + nextBtn.id);
console.log("Clicked button Id: " + e.target.id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn-1" class="buttons">next</button>
<button id="btn-2" class="buttons">previous</button>

你正在做

this.next_fs = $(this)

但是,之前您将其设置为FormController

this.nextBtn.on("click", this.nextClicked.bind(this));

所以你正在做的是

this.next_fs = $( (FormController)this);

你期望jQuery使用类实例,而不是事件对象。

我强烈建议您不要在事件处理上下文中使用$(this)this可以更改其含义,如代码中断在示例中所示。

始终使用 event.target 或 event.currentTarget。我更喜欢currentTarget因为它指向事件绑定的元素,而不是该元素中更深层次的元素。

所以你的代码应该是

nextClicked(e) {
this.next_fs = $(e.currentTarget)
.parent()
.next(); // this is the next fieldset
// some actions...
}

最新更新