Knockoutjs 学习系列(二)花式捆绑
内容摘要
在上一篇Knockoutjs 学习系列(一)ko初体验文章中提到,ko中的 data-bind = "XX:OO"绑定大法除了可以绑定text、value等内容,还可以绑定visible、style等外观属性,也可以绑定click
文章正文
在上一篇Knockoutjs 学习系列(一)ko初体验文章中提到,ko中的 data-bind = "XX:OO"绑定大法除了可以绑定text、value等内容,还可以绑定visible、style等外观属性,也可以绑定click、textInput等各种事件,甚至还能控制程序流程。各种花式捆绑,绝对满足你的幻想。
下面简单讲讲各种绑定的使用,主要根据被绑定的属性分成表现类、流程类和交互类三种。
表现类属性
表现类的绑定属性有visible、text、html、css、style、attr几种,除了css表示css的class之外,其他都很好理解。当然了,style里面的命名要与js一致,要去掉-改成驼峰命名,示范如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!--HTML code--> <div data-bind= "visible: shouldShowMessage" >You will see this message only when "shouldShowMessage" holds a true value.</div> <div>Today's message is: <span data-bind= "text: myMessage" ></span></div> <div data-bind= "html: details" ></div> <div data-bind= "css: { profitWarning: currentProfit() < 0 }" >CSS class binding test</div> <div data-bind= "style: { color: currentProfit() < 0 ? 'red' : 'black' }" >CSS style binding test</div> <a data-bind= "attr: { href: url, title: urltitle }" >Report</a> // js code var viewModel = { shouldShowMessage: ko.observable(true), // Message initially visible myMessage: ko.observable(), // Initially blank details: ko.observable(), // Initially blank currentProfit: ko.observable(150000), // Positive value, so initially we don't apply the "profitWarning" class currentProfit: ko.observable(150000), // Positive value, so initially black url: ko.observable( "year-end.html" ), urltitle: ko.observable( "Report including final year-end statistics" ) }; ko.applyBindings(viewModel); // apply binds |
效果是这样的:
上一篇文章里面也说过,XXOO里面除了传单个的属性,也可以传JSON对象,也就是说可以组合绑定属性,比如说:
1 2 3 4 | <!--HTML code--> <div data-bind= "{visible: shouldShowMessage, text: myMessage, css: { profitWarning: currentProfit() < 0 }}" > You will see this message only when "shouldShowMessage" holds a true value. </div> |
效果当然是这样的:
http://knockoutjs.com/documentation/introduction.html
代码注释