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