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}}">×</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>
下面说明一些重要的点:
引用Polymer.html,这是创建Polymer元素的必要条件
使用< polymer-element > 创建新元素,通过name属性声明元素名称
使用< template > 来封装元素
使用 {{}} 来声明双向绑定的属性
创建好指令后,我们就可以使用该指令了。 创建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就能看到下面的效果~
推荐文章
2025-01-18
2024-11-28
2024-11-09
2024-10-25
2024-06-25
2024-01-04
2023-11-06
2023-10-30
2023-10-13
2023-10-10
稳定
产品高可用性高并发贴心
项目群及时沟通专业
产品经理1v1支持快速
MVP模式小步快跑承诺
我们选择声誉坚持
10年专注高端品质开发