我创建了一个简单的crud app,它使用localstorage来保存和检索对象。现在我想用Handlebars.js替换连接JS + HTML的丑陋函数。我在HTML模板中显示来自本地存储的数据时遇到问题 - 我是否必须编写自定义手柄帮助程序,或者有一个简单的解决方案?
有我的代码 https://codepen.io/KamilNaja/pen/dWXYdd
HTML部分
<div id="output"></div>
<script id="tpl" type="text/x-handlebars-template">
{{#each itemData}}
{{name}}
{{/each}}
</script>
JS - 我想使用渲染功能
var app = {
data: [],
init: function () {
this.cacheDom();
this.bindEvents();
this.render();
},
render: function () {
app.getFromLocalStorage();
var itemData = app.items;
var source = document.getElementById("tpl").innerHTML;
var template = Handlebars.compile(source);
document.getElementById("output").innerHTML = template(itemData);
},
cacheDom: function () {
this.list = document.getElementById("list");
this.addInput = document.getElementById("addInput");
this.addBtn = document.getElementById("addBtn");
this.document = $(document);
},
bindEvents: function () {
this.addBtn.addEventListener("click", app.addItem);
this.document.on("change", ".itemSelect", function (e) {
if (this.value === "erase") {
app.deleteItem(e);
} else if (this.value === "edit") {
app.editItem(e);
}
});
},
saveToLocalStorage: function () {
localStorage.setItem("app.items", JSON.stringify(app.items));
},
getFromLocalStorage: function () {
var retrievedObject = localStorage.getItem("app.items");
app.items = retrievedObject;
},
displayItem: function () {
app.getFromLocalStorage();
var data = "";
//put into handlebars
for (var i in this.items) {
var optionValue =
'<select class="itemSelect">' +
'<option hidden value="unchosen">Options</option>' +
'<option value="edit">Edit</option>' +
'<option value="erase">Erase</option>' +
'</select></li></span>';
//nadaj kolejno id
data += '<li class="listItem"><span id=' + i + ">" + app.items[i].name + optionValue;
}
app.list.innerHTML = data;
},
editItem: function (e) {
app.getFromLocalStorage();
var tableItemNumber = e.target.parentNode.id;
var editItemValue = prompt("Edytuj");
if (editItemValue.length === 0) {
alert("Formularz jest pusty");
}
app.items[tableItemNumber].name = editItemValue;
app.saveToLocalStorage();
app.displayItem();
},
};
app.init();
编辑 我找到了答案。 HTML代码将是相同的。 渲染函数看起来像这样
displayItem: function () {
app.getFromLocalStorage();
var data = "";
var source = document.getElementById("tpl").innerHTML;
var template = Handlebars.compile(source);
//below most important part
var html = template(app);
document.getElementById("output").innerHTML = html;
}
此代码效果很好。