文章從(http://ibeginner.sinaapp.com)遷移過來,歡迎訪問原頁面。javascript
Ember提供的表單元素都是通過封裝的,封裝成了view組件。通過解析渲染以後就會生成普通的HTML標籤。更多詳細信息你能夠查看他們的實現源碼:Ember.TextField、Ember.Chechbox、Ember.TextArea。html
按照慣例,先建立一個route:ember generate route form-helper。java
{{! //app/templates/form-helper.hbs }} {{input name="username" placeholder="your name"}}
其中可使用在input助手上的屬性有不少,包括readonly、value、disabled、name等等,更多有關的屬性介紹請移步官網介紹。git
注意:對於使用在input助手上的屬性是否是使用雙引號括住是有區別的。好比value=」helloworld」和value=helloworld渲染以後的結果是不同的,第一種寫法是直接把「helloworld」這個字符串賦值設置到value上,第二種寫法是從上下文獲取變量helloworld的值再設置到value上,一般是在controller或者route設置的值。github
看下面2行代碼的演示結果:app
{{input name="username" placeholder="your name" value="model.helloworld"}} <br><br> {{input name="username" placeholder="your name" value=model.helloworld}}
修改對應的route類,重寫model回調,返回一個字符串;或者你能夠在模板對應的controller類設置。好比下面的第二段代碼(使用命令ember generate controller form-helper獲得模板對應的controller類。ide
)。函數
// app/routes/form-helper.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return { helloworld: 'The value from route...' } } });
在controller類設置測試數據。測試
// app/controllers/form-helper.js import Ember from 'ember'; export default Ember.Controller.extend({ helloworld: 'The value from route...' });
對應的,若是你使用的是controller設置測試數據,那麼你的模板獲取數據的方式就要稍微修改下。去掉前綴「model.」。controller不須要在回調中設置測試數據,可用直接定義成controller的屬性。ui
{{input name="username" placeholder="your name" value=helloworld}}
運行結果以下;
你能夠想一想下,咱們日常寫過的javascript代碼,不是可用直接在input輸入框上使用javascript的函數,同理的,input助手上可使用javascript函數,不過使用方式有點差異,請看下面示例。好比按enter鍵觸發指定的事件、失去焦點觸發事件等等。
首先編寫input輸入框,獲取input輸入框的值有點不按常理=^=。在controller類獲取input輸入框的值是經過不用雙引號的value屬性獲取的。
按enter鍵觸發 {{input value=getValueKey enter="getInputValue" name=getByName placeholder="請輸入測試的內容"}}
// app/controllers/form-helper.js import Ember from 'ember'; export default Ember.Controller.extend({ actions: { getInputValue: function() { var v = this.get('getValueKey'); console.log('v = ' + v); var v2 = this.get('getByName'); console.log('v2 = ' + v2); } } });
輸入測試內容後按enter鍵。
最後的輸出結果有那麼一點點意外。v的值是正確的,v2倒是undefined。可見在controller層獲取頁面的值是經過value這個屬性而不是name這個屬性。跟咱們日常HTML的input有點不同了!!這個須要注意下。
checkbox這個表單元素也是通過Ember封裝了,做爲一個組件使用。使用過程須要注意的問題與前面的input是同樣的,屬性是否是使用雙引號所起的做用是不同的。
checkbox{{input type="checkbox" checked=isChecked }}
你能夠在controller類增長一個屬性isChecked並設置爲true,checkbox將默認爲選中。
// app/controllers/form-helper.js import Ember from 'ember'; export default Ember.Controller.extend({ isChecked: true });
{{textarea value=key cols="80" rows="3" enter="getValueByV"}}
一樣的也是經過value屬性獲取輸入的值。
本篇簡單的介紹了經常使用的表單元素,使用的方式比較簡單,惟一須要注意的是獲取的輸入框輸入值的方式與日常使用的HTML表單元素有點差異。其餘的屬性設置(好比CSS樣式)基本上與普通的HTML表單元素沒什麼差異。