gpt4 book ai didi

javascript - Javascript 中的类 - 作为参数传递方法后属性未定义

转载 作者:行者123 更新时间:2023-12-03 02:17:04 25 4
gpt4 key购买 nike

任何人都可以解释一下为什么我在类实例化时收到第一条控制台消息:“1 .list-group-item”,但在按下“.remove_track”按钮后,我得到 this.DOM.TrackItems 为未定义?非常感谢任何帮助或建议。

class MyList
constructor() {
this.DOM = {
ParentNode: '#mylist',
AddTrackButton: '#add_track',
RemoveTrackButtons: '.remove_track',
TrackItems: '.list-group-item'
};

this.bind(this.DOM.ParentNode, this.DOM.RemoveTrackButtons, 'click', this.removeTrack);

};

//jQuery on/off methods
bind(parentSelector, childSelector, eventName, functionName) {
console.log('1 ' + this.DOM.TrackItems);
$(parentSelector).on(eventName, childSelector, functionName);
};

unbind(parentSelector, childSelector, eventName, functionName){
$(parentSelector).off(eventName, childSelector, functionName);
}

removeTrack(evt) {
evt.preventDefault();
console.log('2 ' + this.DOM.TrackItems);
}
}

//编辑:

Here's a jsfiddle

最佳答案

问题与上下文 this 的范围有关,该方法是使用事件 click 中处理程序的上下文,特别是单击的按钮而不是类MyList

另一种方法是使用函数bind绑定(bind)上下文:

                   +----- This is the object MyList
|
v
functionName.bind(this); <---- This call returns a new function bound with
^ the specific context.
|
+---- This function binds the context

如果您需要访问被单击的元素,可以使用参数event

class MyList {
constructor() {
this.DOM = {
ParentNode: '#mylist',
AddTrackButton: '#add_track',
RemoveTrackButtons: '.remove_track',
TrackItems: '.list-group-item',
Output: '#output'
}

this.bind(this.DOM.ParentNode, this.DOM.RemoveTrackButtons, 'click', this.removeTrack);
};

bind(parentSelector, childSelector, eventName, functionName) {
$(this.DOM.Output).html('Called Bind'); //works
// This is the line with a fix.
$(parentSelector).on(eventName, childSelector, functionName.bind(this));
};

unbind(parentSelector, childSelector, eventName, functionName) {
$(this.DOM.Output).html('Called Unbind');
$(parentSelector).off(eventName, childSelector, functionName);
}

removeTrack(evt) {
evt.preventDefault();
console.log(evt.target);
console.log(this); // This is just to show the content of this.
$(this.DOM.Output).html('Called removeTrack');
}
}

x = new MyList();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mylist">
<button class="remove_track">
HELLO
</button>
<div id="output">
</div>
</div>

关于javascript - Javascript 中的类 - 作为参数传递方法后属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49331214/

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