在JavaScript中,使用bind()删除作为事件侦听器添加的函数的最佳方法是什么?
例
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.myButton.addEventListener("click", this.clickListener.bind(this));
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", ___________);
};
})();
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法就是跟踪每个添加了bind的侦听器.
以上示例使用此方法:
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.clickListenerBind = this.clickListener.bind(this);
this.myButton.addEventListener("click", this.clickListenerBind);
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", this.clickListenerBind);
};
})();
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
<div id="foo">
<div></div>
<div id="bar"></div>
<div></div>
</div>
Run Code Online (Sandbox Code Playgroud)
如何使“条形图”的顶部相对于其原始位置处于-5px的位置,并且也从正常流程中移除?
#bar {
position: relative;
top: -5px;
}
Run Code Online (Sandbox Code Playgroud)
由于未从正常流程中删除“栏”,因此无法正常工作
#foo {
position: relative;
}
#bar {
position: absolute;
top: -5px;
}
Run Code Online (Sandbox Code Playgroud)
由于“ bar”的顶部相对于“ foo”放置了-5px,因此无效
我知道静态函数的名称只在声明它的文件(翻译单元)中可见.这使得封装成为可能.
但是静态函数通常在源文件中声明,因为如果你在头文件中执行它,你最终会得到它的多个实现(我认为这不是我的意图static
).
例:
main.c中
#include "functions.h"
int main()
{
FunctionA();
FunctionB(); // Can't call regardless of "static".
return 0;
}
Run Code Online (Sandbox Code Playgroud)
functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
void FunctionA();
#endif /* FUNCTIONS_H */
Run Code Online (Sandbox Code Playgroud)
functions.c
#include "functions.h"
#include <stdio.h>
static void FunctionB(); // Same whether "static" is used or not.
void FunctionA()
{
printf("A");
}
void FunctionB()
{
printf("B");
}
Run Code Online (Sandbox Code Playgroud)
那么什么时候static
有用?