如何独立使用Polymer TemplateBinding库

How to use Polymer TemplateBinding library standalone?

本文关键字:Polymer TemplateBinding 何独立 独立      更新时间:2023-09-26

Polymer的TemplateBinding库扩展了HTML的功能模板元素,使其能够创建、管理和删除绑定到JavaScript中定义的数据的内容实例。虽然内部聚合物,它也是有用的独立。

TemplateBinding是一个独立的库,不依赖于Polymer。因此,从理论上讲,在没有聚合物的情况下使用它是可能的。

我找不到任何如何使用此单机版的示例。

例如,我有这样的标记

<ul>
    <template id="colors" repeat="{{ colors }}">
      <li style="color: {{ color }}">The style attribute of this list item is bound</li>
    </template>
</ul>

和json

colors: [
          { color: 'red' },
          { color: 'blue' },
          { color: 'green' },
          { color: 'pink' }
        ]

我正在寻找一个接受模板和数据并返回处理后的标记的函数。

您所说的独立是什么意思?你的意思是在聚合物网络组件之外使用聚合物?

如果是,您可以使用自动绑定属性,例如

<template id="colors" repeat="{{ colors }}" is="auto-binding">

这将允许Polymer在Light DOM(页面上的任何地方)中查看您的模板

这是一个工作Fiddle:http://jsfiddle.net/Lm7tgbLo/

HTML代码:

<script src="http://www.polymer-project.org/polymer.min.js"></script>
<ul>
    <template id="colors" repeat="{{color in colors}}" is="auto-binding">
      <li style="color: {{ color }}">The style attribute of this list item is bound</li>
    </template>
</ul>

JavaScript:

window.addEventListener('polymer-ready', function (e) {
    document.getElementById("colors").colors = ['red', 'blue', 'green', 'pink'];
});

如果你只是在寻找一个好的基于模板的UI库。我推荐RactiveJS。https://ractive.js.org/

开始很容易。

模板

<p>{{greeting}} {{name}}!</p>

JS代码

var ractive = Ractive({
  target: output,
  template: template,
  data: { greeting: 'Hello', name: 'world' }
});