MVVM是一種架構思想,是一種解決問題的方式,對於一個項目,一個功能模塊,你可以選擇使用MVVM的架構來實現,而knockoutjs只是實現MVVM的一種工具,它是在前端實現的,這一點,我們必須的清楚.
思想
下面說一下這講的重點,前台和后台的分工問題,占占認為,前台只負責頁面及頁面CSS及實現效果的JS,而后台的工作包括業務的處理,數據的持久化,前台數據的綁定(knockoutjs)等等.
實踐
下面是前台HTML代碼
<table border="1"> <tr> <th>QuestionInfoID </th> <th>用戶</th> <th>類型</th> <th>知識點</th> <th>難度</th> <th>日期</th> <th>年級</th> <th>學科</th> <th>圖像</th> </tr> <tbody data-bind="foreach:model"> <tr> <td data-bind="text:QuestionInfoID"></td> <td> <span data-bind="if:Partner_Info"><span data-bind="text:Partner_Info.AccountName"></span></span> <span data-bind="if:User_Info"><span data-bind="text:User_Info.RealName"></span></span> </td> <td data-bind="text:OwnerType"></td> <td data-bind="text:Knowledge"></td> <td data-bind="text:Difficulty"></td> <td data-bind="text:AddTime"></td> <td data-bind="foreach:Question_Point_R"><span data-bind="text:Point_Info.Grade"></span></td> <td data-bind="foreach:Question_Point_R"><span data-bind="text:Point_Info.Subject"></span></td> <td> <img width="21" height="21" src="1.jpg" onerror="errorImg(this)" /></td> </tr> </tbody> </table>
下面是后台的knockoutjs代碼
@Html.Pager(Model)//C#數據分頁 <script type="text/ecmascript"> //圖像加載出錯時的處理 function errorImg(img) { img.src = "http://www.baidu.com/img/bdlogo.gif"; img.onerror = null; } var model = ko.observableArray(@Html.Raw(Json.Encode(Model)));//從后台得到數據集合,並轉化為json對象 ko.applyBindings(model); </script>
運行截圖
說明
在這個例子中,我們使用了knockoutjs里的if,foreach等關鍵字,if可以判斷一個對象是否為空,而foreach可以把集合對象遍歷出來.