templatebinding在前端開發中的應用

一、templatebinding twoway

templatebinding twoway是一種使數據綁定流實現雙向同步的方法。當綁定一個input元素時,它不僅讀取屬性值顯示在界面上,且當輸入框中的輸入發生變化時,數據綁定也會將值存儲到屬性中。為了使此功能工作,我們需要引入一個構造器——InputData,它將要被綁定到表格中的每個單元格。我們的目標是使我們的InputData對象儘可能地表現為一個簡單對象,只在它被用於同步時才需要學習模板綁定的細節。

class InputData {
  constructor(value = "", valid = true) {
    this.value = value;
    this.valid = valid;
  }
}

function bindInput(inputElement, data, property) {
  inputElement.value = data[property];

  inputElement.oninput = function () {
    data[property] = inputElement.value;
  };
}

let input = new InputData("Initial value");

bindInput(document.getElementById("inputElement"), input, "value");

在上面的代碼示例中,我們定義了一個InputData類,並在InputData實例化之後將InputData傳遞到bindInput()函數來執行綁定。bindInput()函數被告知數據綁定的實際值(在這裡是InputData.value屬性),並將輸入元素傳遞到該函數中。

二、templatebinding content

templatebinding content的作用是,使模板綁定可以將數據綁定到元素的innerHTML屬性。在實際應用中,很少直接使用innerHTML屬性,因為這種做法會將字元串解析為節點。這將消耗大量的內存,因為該過程會創建許多臨時對象。但是,如果正確使用innerHTML,那麼它可以更改節點的內部結構,而不會冒著解析字元串的風險。

class BoundElement extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `
      
        :host {
          display: block;
        }
      
      
    `;
  }

  static get observedAttributes() {
    return ["text"];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    this.shadowRoot.querySelector("slot").textContent = newValue;
  }
}

customElements.define("bound-element", BoundElement);

let boundElement = document.querySelector("bound-element");

boundElement.setAttribute("text", "Some text");

在上面的代碼示例中,我們先定義了一個BoundElement類,並在該類中定義了元素的DOM模板,然後我們使用customElements.define()方法來使用元素名稱註冊該元素類。最後,我們通過調用setAttribute()方法來為元素設置text屬性,同時也在該屬性發生更改時觸發了attributeChangedCallback()方法。

三、templatebinding 無法綁定路徑

templatebinding可能無法綁定路徑,因為一些數據綁定系統實際上是靜態的部分。當這種情況發生時,我們可以使用各種簡便方法,如藉助屬性的語法糖,在表達式所在的對象之前添加一個引用,以使該屬性不再成為綁定路徑的一部分。

class App {
constructor() {
this.name = "TemplateBinding";

this.person = {
firstName: "John",
lastName: "Doe"
};
}

getFullName() {
return this.person.firstName + " " + this.person.lastName;
}
}

let app = new App();

let template = `
Hello, {{person.firstName}} {{person.lastName}}!

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/155376.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-17 02:41
下一篇 2024-11-17 02:41

發表回復

登錄後才能評論