文本框是頁面中最常用的輸入組件,它的默認使用方式如下:
<input type='text'/>
當然,這里的 `type='text' 可以略去不寫。大部分情況下,使用默認的文本框作為輸入組件是沒什么問題的,但在具體的項目中,難免會有功能擴展的需求。這里僅以如何增加文本框數據的格式化輸入輸出能力為例說明如何擴展原生的文本框組件。除了本章的內容,你也可以參考官方文檔中的 參數映射 一章。
目標組件的功能分析
對于原生的文本框,我們獲取到的值是文本類型的,就像下面的示例所展示的:
Example: { xml: "<input id='input' value='text'/>", fun: function (sys, items, opts) { console.log(typeof this.prop("value")); // string }}
如果需要其它類型的數值,就需要對獲取到的數據進行格式化操作。比如,如果需要整型數,就需要用到 parseInt 函數;如果需要浮點型數,就需要用到 parseFloat 函數。如果我們能夠將格式化數據的操作封裝起來,那使用起來一定會相當的方便。為了明確我們的預期,不妨先給出目標組件的使用示例。
Index: { xml: "<div id='index'>/ <TextBox id='foo'/>/ <TextBox id='bar' format='int'/>/ </div>", fun: function (sys, items, opts) { items.foo.value = "hello, world"; items.bar.value = 27.1828; console.log("foo", items.foo.value); console.log("bar", items.bar.value); }}
此示例實例化了兩個組件 Input。組件 Input 允許接收一個 format 參數作為其靜態接口輸入,并提供一個屬性 value 作為其動態輸入輸出接口。format 參數有三種可能的值:string (默認)、int 以及 float。這三種值分別對應三種數據類型:字符串型、整型和浮點型。屬性 value 根據 format 的值來進行格式化輸入輸出。示例的輸出結果應該會是下面這樣子:
hello, world
227
目標組件的實現
為了完成上面的目標組件,我們先給出一個文本框的組件框架。
TextBox: { xml: "<input id='input' type='text'/>", opt: { format: "string" }, fun: function (sys, items, opts) { var parse = {"int": parseInt, "float": parseFloat, "string": String}[opts.format]; function getValue() { // 這里需要獲取 input 的值并根據 opts.format 值選擇適當的格式化函數, } function setValue(value) { // 這里需要根據 opts.format 值選擇適當的格式化函數,對 value 進行格式化后同去賦值 } return Object.defineProperty({}, "value", { get: getValue, set: setValue }); }}
上面關鍵的地方在于格式化函數的選取,為了簡單化,我們采用的是表查詢方式。在組件初始化階段該函數就已經準備就緒了,上述的 parse 函數即所需的格式化函數。不過需要注意的是,該組件的格式化函數類型在組件初始化時就固定了。如果需要可變的格式化函數,你需要對組件做些修正。好了,下面可以給出完整的的文本框組件了。
TextBox: { xml: "<input id='input' type='text'/>", opt: { format: 'string' }, map: { attrs: { input: "disabled value placeholder readonly" } }, fun: function (sys, items, opts) { var parse = {"int": parseInt, "float": parseFloat, "string": String}[opts.format]; function getValue() { return parse(sys.input.prop("value")); } function setValue(value) { sys.input.prop("value", parse(value)); } return Object.defineProperty({}, "value", { get: getValue, set: setValue }); }}
另外請注意,上面組件添加了部分屬性映射的內容,這可以在具體的項目中根據需要進行增刪。
本系列文章基于 xmlplus 框架。如果你對 xmlplus 沒有多少了解,可以訪問 www.xmlplus.cn。這里有詳盡的入門文檔可供參考。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答