簡體   English   中英

用不同的 arguments 在另一個類的屬性中綁定對象的方法

[英]Binding an object's method in another class's property with different arguments

這是我正在處理的文件的精簡版本。

所以,有這個 Object 有這個方法,

const A = {
          dispatchEvent(el, component, eventName, ...args) {
          el.dispatchEvent(new CustomEvent("gsuiEvents", {
              bubbles: true,
              detail: { component, eventName, args },
          })
     );
 }

還有

class B extends HTMLElement {
        constructor() {}
        super();
        this._dispatch = A.dispatchEvent.bind(
          null,
          this,
          "someItem"
        );

     _oninputProp(prop, val) {
        this._dispatch("liveChange", prop, val);
     }
}

如果您查看Class B ,被綁定的 dispatchEvent 方法有 (null, this, "someItem") 作為參數,而在Object A上,有(el, component, eventName, ...args)

我想了解發生了什么。 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.

很抱歉提出這樣的問題,請多多包涵。 謝謝你。

這是設置它的另一種方法:

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);
     }
}

bind 的第一個參數是綁定的 function 將用作this的任何參數。

在您的情況下,您想在進行綁定的元素上調用dispatchEvent ,即 class B 的實例。

因此,要實現這一點,您應該在綁定的 function 中傳遞要用作this的元素的this

arguments 都是正確的。 這里發生的事情是這樣的,

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]

多虧了您的 MDN 參考鏈接。 我對此一無所知,我所需要的只是清晰。 再次感謝你,克里斯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM