之后我會零散的翻譯一些學習Knockout的文檔,希望可以幫助需要幫助的人快速學習Knockout,深入理解MVVM,如果理解有錯誤,歡迎指點。
今天簡單記錄下屬性綁定
屬性綁定 |
Purpose
The attr binding provides a generic way to set the value of any attribute for the associated DOM element. This is useful, for example, when you need to set the title attribute of an element, the src of an img tag, or the href of a link based on values in your view model, with the attribute value being updated automatically whenever the corresponding model property changes.
屬性綁定為關聯的DOM元素設置任意屬性的提供了通用方式。這是有用的,當你需要在view模型設置一個元素的title屬性,圖片標簽的源屬性,或者是鏈接的href屬性,而這些屬性
是需要隨着視圖模型即UI層變化而變化,這時就可以使用屬性綁定
Example
<a data-bind="attr: { href: url, title: details }"> Report </a> <script type="text/javascript"> var viewModel = { url: ko.observable("year-end.html"), details: ko.observable("Report including final year-end statistics") }; </script>
參數 |
Parameters
Main parameter
You should pass a JavaScript object in which the property names correspond to attribute names, and the values correspond to the attribute values you wish to apply.
如上面例子所示 意思即為 title與viewModel的details,url與viewModelurl對於
If your parameter references an observable value, the binding will update the attribute whenever the observable value changes. If the parameter doesn’t reference an observable value, it will only set the attribute once and will not update it later.
如果參數是一個被觀察的值,那么當觀察值變化時,綁定會自動更新。否則,屬性值只hi設置一次,之后不會變化
怎么理解呢
在上圖的例子中
如果
details: ko.observable("Report including final year-end statistics") 換成 details:'home.cnblogs.co'
那么 鏈接值就不會隨着details的變化而變化
Note: Applying attributes whose names aren’t legal JavaScript variable names
應用屬性名不是合法的變量名
<div data-bind="attr: { data-something: someValue }">...</div>
because data-something isn’t a legal identifier name at that point. The solution is simple: just wrap the identifier name in quotes so that it becomes a string literal, which is legal in a JavaScript object literal. For exampl
解決方法很簡單,只需要把屬性名字寫在引號中,js就把它解析為string類型
<div data-bind="attr: { 'data-something': someValue }">...</div>
注:可能Applying attributes whose names aren’t legal JavaScript variable names 即為綁定錯誤的提示語句,如果有錯誤 在chome的控制台里可以查看
參考:
http://knockoutjs.com/documentation/attr-binding.html