列表組件是極其常用的一類組件,是許多視圖組件系統的必須包含的。列表可以做的很簡單,只顯示簡潔的內容。列表也可以做的很復雜,用于展示非常豐富的內容。
組成元素
列表離不開列表項以及包含列表項的容器。下面是最簡單的列表組件,它包含一個列表項組件 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"}; }); }}
新聞熱點
疑難解答
圖片精選