一、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/n/155376.html
微信扫一扫
支付宝扫一扫