Polymer


关于Polymer的介绍我就不多说了,这里只简单介绍一下。

Polymer是Google在2013年发布的Web UI库,使用了很多HTML5的技术。 这里主要通过一个TODO例子来讲解如何创建一个自己的Element。

首先,下载Polymer库,我们通过bower来安装Polymer

$ bower install polymer

安装完成后我们先创建属于自己的element

$ touch todo-element.html

使用文本编辑器,敲入下面的代码

<link rel="import" href="bower_components/polymer/polymer.html"><polymer-element name="todo-element"><template>
    <style>
        ul li{
            list-style: none;
        }
        a[on-click]{
            cursor: pointer;
        }
    </style>
    <input type="text" value="{{item}}">
    <button on-click="{{addItem}}">add</button>
    <ul>
        <template repeat="{{item,itemIndex in list}}">
            <li>
                <input type="checkbox" value="{{item.checked}}">
                <span>{{item.text}}</span>
                <a data-index="{{itemIndex}}" on-click="{{removeItem}}">&times;</a>
            </li>
        </template>
    </ul>
    <button on-click="{{doArchive}}">archive</button></template><script>Polymer({
    list: [],
    addItem: function(){
        this.list.push({
            text: this.item,
            checked: false
        });
        this.item = '';
    },
    removeItem: function(e, detail, sender){
        var index = sender.attributes['data-index'].value;
        this.list.splice(index,1);
    },
    doArchive: function(){
        for(var i in this.list){
            if(this.list[i].checked){
                this.list.splice(i,1);
            }
        }
    }});</script></polymer-element>

下面说明一些重要的点:

  1. 引用Polymer.html,这是创建Polymer元素的必要条件

  2. 使用< polymer-element > 创建新元素,通过name属性声明元素名称

  3. 使用< template > 来封装元素

  4. 使用 {{}} 来声明双向绑定的属性

创建好指令后,我们就可以使用该指令了。 创建index.html

$ touch index.html

编辑该文件,引入我们创建的指令

<!DOCTYPE html><html>
  <head>
      <script src="bower_components/webcomponentsjs/webcomponents.js"></script>
      <link rel="import" href="todo-element.html">
  </head>
  <body>
      <todo-element></todo-element>
  </body></html>

最后我们用web服务器来访问index.html就能看到下面的效果~TODO

稳定

产品高可用性高并发

贴心

项目群及时沟通

专业

产品经理1v1支持

快速

MVP模式小步快跑

承诺

我们选择声誉

坚持

10年专注高端品质开发
  • 返回顶部