[英]Binding an object's method in another class's property with different arguments
This is a stripped down version of a file i'm working on.这是我正在处理的文件的精简版本。
So, there's this Object that has this method,所以,有这个 Object 有这个方法,
const A = {
dispatchEvent(el, component, eventName, ...args) {
el.dispatchEvent(new CustomEvent("gsuiEvents", {
bubbles: true,
detail: { component, eventName, args },
})
);
}
and there's还有
class B extends HTMLElement {
constructor() {}
super();
this._dispatch = A.dispatchEvent.bind(
null,
this,
"someItem"
);
_oninputProp(prop, val) {
this._dispatch("liveChange", prop, val);
}
}
If you look at the Class B , the dispatchEvent method being bound has (null, this, "someItem") as the parameters whereas on Object A , there's (el, component, eventName, ...args) .如果您查看Class B ,被绑定的 dispatchEvent 方法有 (null, this, "someItem") 作为参数,而在Object A上,有(el, component, eventName, ...args) 。
I want to understand whats going on.我想了解发生了什么。 Will the this._dispatch property have the function that's contained in Object A ?
this._dispatch属性是否具有包含在Object A中的 function ?
also, if you look at the arguments on Class B 's _oninputProp() method, there's different type of arguments which is different from Object A 's dispatchEvent() method. also, if you look at the arguments on Class B 's _oninputProp() method, there's different type of arguments which is different from Object A 's dispatchEvent() method.
Sorry for such a question, please bear with me.很抱歉提出这样的问题,请多多包涵。 Thank you.
谢谢你。
This is an alternative way to set it up:这是设置它的另一种方法:
const A = {
dispatchEvent(component, eventName, ...args) {
this.dispatchEvent(new CustomEvent("gsuiEvents", {
bubbles: true,
detail: { component, eventName, args },
})
);
}
class B extends HTMLElement {
constructor() {}
super();
this._dispatch = A.dispatchEvent.bind(
this,
"someItem"
);
_oninputProp(prop, val) {
this._dispatch("liveChange", prop, val);
}
}
The first argument to bind is whatever the bound function will use as this
. bind 的第一个参数是绑定的 function 将用作
this
的任何参数。
In your case you want to invoke dispatchEvent
on the element that made the binding, ie the instance of class B.在您的情况下,您想在进行绑定的元素上调用
dispatchEvent
,即 class B 的实例。
So to achieve this you should pass the element's this
to be used as this
in the bound function.因此,要实现这一点,您应该在绑定的 function 中传递要用作
this
的元素的this
。
The arguments are all correct. arguments 都是正确的。 Whats happening here is this,
这里发生的事情是这样的,
function list() {
return Array.prototype.slice.call(arguments);
}
const list1 = list(1, 2, 3);
// [1, 2, 3]
// Create a function with a preset leading argument
const leadingThirtysevenList = list.bind(null, 37);
const list2 = leadingThirtysevenList();
// [37]
const list3 = leadingThirtysevenList(1, 2, 3);
// [37, 1, 2, 3]
All thanks to your MDN reference link.多亏了您的 MDN 参考链接。 I was in the dark with this and all i needed was clarity.
我对此一无所知,我所需要的只是清晰。 Thank you again, Chris!
再次感谢你,克里斯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.