Knockout 組件嵌套模板書寫注意問題,knockout嵌套
在進行Knockout組件嵌套模板編寫時,會有多個引號的使用,特別是單引號和雙引號同時使用時,這裡有一個例子【1】:
templateEngine.addTemplate("ko_simpleGrid_grid", "\ <table class=\"ko-grid\" cellspacing=\"0\" data-bind=\"\">\ <thead>\ <tr data-bind=\"foreach: columns\">\ <th><div><span class=\"adjustCol_left\"> </span><span data-bind=\"text: headerText\"></span> \ <span class=\"adjustCol_right\" data-bind=\"event:{mousedown:$parent.headTdMousedown}\"> </span></div></th>\ </tr>\ </thead>\ <tbody data-bind=\"foreach: itemsOnCurrentPage\">\ <tr data-bind=\"foreach: $parent.columns\">\ <td data-bind=\"attr:{ prop1:typeof rowText == 'function' ? rowText($parent) : $parent[rowText] }, click:$root.cellEdit \"> \ <div data-bind='component: {name:\"ColumnEditor\", params:{editortype:editortype, value:typeof rowText == \"function\" ? rowText($parent) : $parent[rowText], editing:false}}'></div>\ </td>\ </tr>\ </tbody>\ </table>");
在這裡,注意這一行:
(1)正確的寫法
<div data-bind='component: {name:\"ColumnEditor\", params:{editortype:editortype, value:typeof rowText == \"function\" ? rowText($parent) : $parent[rowText], editing:false}}'></div>\value的賦值邏輯為:判斷表格模型的父模型rowText資料類型是否為function,若為function則執行該函數擷取值;否則使用父模型中的值。在這裡整個一行字串包含在大的模板字串中,data-bind使用了單引號來書寫綁定內容,這時,若再在綁定裡使用單引號,則需要轉義,如上行(1)。
假如寫成這樣,則是錯誤的:
(2)錯誤的寫法
<div data-bind='component: {name:\"ColumnEditor\", params:{editortype:editortype, value:typeof rowText == 'function' ? rowText($parent) : $parent[rowText], editing:false}}'></div>\雖然這是一個本應該注意的問題,但在使用情境較複雜的情形,很容易忘記轉義,而錯誤的寫法卻導致錯誤非常難查。
作為經驗,進行記錄,以供碰到類似問題時作為參考。
參考:
【1】Page Grid:http://knockoutjs.com/examples/grid.html