之后我会零散的翻译一些学习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的控制台里可以查看
参考: