列表组件是极其常用的一类组件,是许多视图组件系统的必须包含的。列表可以做的很简单,只显示简洁的内容。列表也可以做的很复杂,用于展示非常丰富的内容。
组成元素
列表离不开列表项以及包含列表项的容器。下面是最简单的列表组件,它包含一个列表项组件 Item 以及一个列表项容器组件 List。
Item: { xml: "<li id='item'/>"},List: { xml: "<ul id='list'/>"}
此列表组件尽管简单,但所构建的框架为我们的继续扩展奠定了基础。
动态操作
如上定义的列表组件的最基本的用法如下所示。这种用法与原生列表标签的用法没什么区别。我们将进行做进一步的改造。
Example: { xml: "<List id='example'>/ <Item>Item 1</Item>/ <Item>Item 2</Item>/ </List>"}
列表组件普遍包含添加、删除以及修改这三种操作。为简单起见,不妨先来实现这些操作。由于我们定义的列表项足够的简单,所以这里不再定义新的操作接口,而直接使用系统接口。
Example: { xml: "<div id='example'>/ <List id='list'/>/ <button id='append'>append</button>/ <button id='remove'>remove</button>/ <button id='modify'>modify</button>/ </div>", fun: function (sys, items, opts) { sys.append.on("click", function() { sys.list.append("Item").text("Item 1"); }); sys.remove.on("click", function() { sys.list.first() && sys.list.first().remove(); }); sys.modify.on("click", function() { sys.list.first() && sys.list.first().text("Item 2"); }); }}
该示例使用列表的系统函数 append 来追加列表项,并使用列表项的系统函数 remove 来移除列表项,同时还使用列表项的系统函数 text 来修改列表项的数据。
由于上面的列表项所包含的是简单的文本数据,所以上面示例使用 text 函数来操作数据是适合的。现在给出一个包含较复杂数据的列表项,该列表项额外定义了数据操作接口。
Item: { xml: "<li id='item'>/ <span id='color'>red</span> <span id='shape'>square</span> </li>", fun: function (sys, items, opts) { function getValue() { return {color: sys.color.text(), shape: sys.shape.text()}; } function setValue(obj) { sys.color.text(obj.color); sys.shape.text(obj.shape); } return Object.defineProperty({}, "data", { get: getValue, set: setValue}); }}
下面是包含新列表项的列表操作的一个示例。其中对于组件的追加与删除还可以使用系统提供的函数,但对于数据的获取与修正就只能使用新定义的接口了。
Example: { xml: "<div id='example'>/ <List id='list'/>/ <button id='append'>append</button>/ <button id='remove'>remove</button>/ <button id='modify'>modify</button>/ </List>", fun: function (sys, items, opts) { sys.append.on("click", function() { sys.list.append("Item"); }); sys.remove.on("click", function() { sys.list.first() && sys.list.first().remove(); }); sys.modify.on("click", function() { sys.list.first() && items.list.first().data = {color: "blue", shape: "rectangle"}; }); }}
新闻热点
疑难解答
图片精选