我有一个大模板的问题,我想我终于可以在一个小的 jsfiddle 中重现它。当 Ractive.js 的 reset() 和 update() 方法复制模板时,当有一个带有 array.prototype.sort() 的助手并且数据有一个像这样的空对象时,我不理解以下行为:
[
{id : 4, name: "Ringo", username: "Star43"},
{id : 2, name: "Paul", username: "Pmac44"},
{id : 1, name: "John", username: "Jony41"},
{id : 3, name: "George", username: "Harris44"},
{}
]
我不知道这是一个错误还是我不明白的行为。
助手是这样的:
sort : function(arr){
//return arr
arr.sort(function(a, b){
return a.id - b.id
})
return arr
}
如果我取消注释第一个
//return arr
然后 reset() 和 update() 不要复制模板
这是强制性的 jsfiddle:http: //jsfiddle.net/Katio/rfuzxwv8/
还有 Stackoverflow 代码片段:您只需单击重置和更新按钮。
var Section = Ractive.extend({
el: 'container',
template: '#table-template',
data: {
headers: [
{id : 5, name: "Id"},
{id : 7, name: "Name"},
{id : 9, name: "Username"},
{}
],
rows : [
{id : 4, name: "Ringo", username: "Star43"},
{id : 2, name: "Paul", username: "Pmac44"},
{id : 1, name: "John", username: "Jony41"},
{id : 3, name: "George", username: "Harris44"},
{}
],
capitalize : function(string){
return string.toUpperCase()
},
sort : function(arr){
//return arr
arr.sort(function(a, b){
return a.id - b.id
})
console.log("arr.length: " + arr.length)
console.log(arr)
return arr
}
}
});
var rSection = new Section({
})
document.querySelector("#btnreset").addEventListener("click", function(){ rSection.reset() }, false )
document.querySelector("#btnupdate").addEventListener("click", function(){ rSection.update() }, false )
table, td, th{
border: 1px solid black;
margin: 5px 5px 5px 5px;
}
<script src="http://cdn.ractivejs.org/edge/ractive.js"></script>
<script type="x-template" id="table-template">
<table>
<thead>
<tr>
{{#sort(headers)}}
<th> {{name}} </th>
{{/headers}}
</tr>
</thead>
<tbody>
{{#sort(rows)}}
<tr>
<td> {{id}} </td>
<td> {{capitalize(name)}} </td>
<td> {{username}}</td>
</tr>
{{/rows}}
</tbody>
<tbody>
</tbody>
</table>
<input type="button" value = "Ractive.reset()" id="btnreset"/>
<input type="button" value = "Ractive.update()" id="btnupdate"/>
</script>
<div id="container"></div>