gpt4 book ai didi

javascript - Polymer Templatizer 实例和主机之间的数据绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 05:08:08 27 4
gpt4 key购买 nike

我正在尝试使用 Polymer 模板化器创建模板的单个实例,将其附加到 div 中并让数据绑定(bind)在主机和该实例之间工作,但我很难让它工作。

我尝试过的最简单的例子:

HTML

<dom-module id="test-app">
<paper-input label="host" value="{{test}}"></paper-input>
<template id="template">
<paper-input label="instance" value="{{test}}"></paper-input>
</template>
<div id="placehere"></div>
</dom-module>

JS

Polymer({
is: "test-app",
behaviors: [Polymer.Templatizer],
properties: {
test: {
type: String,
value: 'hello',
notify: true,
},
},

ready: function() {
this.templatize(this.$.template);
var clone = this.stamp({test: this.test});
Polymer.dom(this.$.placehere).appendChild(clone.root);
},
});

上面的想法是创建模板的实例,将其放置到“placehere”中,并使两个输入文本框保持同步。

页面加载时,实例已成功创建,两个文本框中的值为“hello”,但更改任一输入框不会执行任何操作。

polymer 页面上的文档似乎有点轻量: https://www.polymer-project.org/1.0/docs/api/Polymer.Templatizer但它提到了 _forwardParentProp 和 _forwardParentPath 的使用。在我的情况下,我到底应该如何实现它们?

最佳答案

正如您已经想到的,您需要实现一些模板化程序的方法。特别是 _forwardParentProp_forwardParentPath 方法。

但在开始之前,我还必须指出自定义元素定义中的另一个错误。在 dom-module 元素中,您可以在没有模板的情况下定义元素的内容。将所有内容包装在 template 元素中至关重要。自定义元素的固定版本将如下所示:

<dom-module id="test-app">
<template>
<paper-input label="host" value="{{test}}"></paper-input>
<template id="template">
<paper-input label="instance" value="{{test}}"></paper-input>
</template>
<div id="placehere"></div>
</template>
</dom-module>

对于Templatizer方法的实现,首先需要存储标记的实例。之后,需要实现的两种方法都或多或少是简单的一句话。

这是自定义元素的完整 JavaScript 部分:

Polymer({
is: "test-app",
behaviors: [Polymer.Templatizer],
properties: {
test: {
type: String,
value: 'hello',
notify: true,
},
},

ready: function() {
this.templatize(this.$.template);
var clone = this.stamp({test: this.test});
this.stamped = clone.root.querySelector('*'); // This line is new
Polymer.dom(this.$.placehere).appendChild(clone.root);
},

// This method is new
_forwardParentProp: function(prop, value) {
if (this.stamped) {
this.stamped._templateInstance[prop] = value;
}
},

// This method is new
_forwardParentPath: function(path, value) {
if (this.stamped) {
this.stamped._templateInstance.notifyPath(path, value, true);
}
},
});

这是一个有效的 JSBin 演示:http://jsbin.com/saketemehi/1/edit?html,js,output

关于javascript - Polymer Templatizer 实例和主机之间的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41587444/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com