数据更改时重新渲染 Handlebars 模板
Rerendering Handlebars template upon data change
我有一个模板,它显示了一个基于 JSON 对象中的某个布尔值的按钮。它可以显示两个不同的按钮。
模板编译代码:
source = $('#some-template').html(); // Get the HTML source of the template
template = Handlebars.compile(source); // Compile it
$('#some-div-container').html(template(someJsonObject));
假设对象看起来像这样:
someJsonObject = {
smeBooleanValue : false,
someOtherValue : 5
};
模板如下所示:
<div id="some-div-container">
<script id="some-template" type="text/x-handlebars-template">
<button type="button" class="btn btn-default btn-lg" onclick="myGreatMethodForDoingThings()">
{{#if smeBooleanValue}} <span class="glyphicon glyphicon-stop" aria-hidden="true"></span> Do something
{{else}} <span class="glyphicon glyphicon-play" aria-hidden="true"></span> Do something else{{/if}}
</button>
</script>
</div>
问题是当 someJsonObject
中的布尔值发生变化时,视图不会更新。我以为这会自动发生(就像 Meteor 中的 Handlebars 一样),但我似乎错了?
在那种情况下:它是如何完成的?我可以有一个重新呈现模板的方法,可以在 setter 中为值调用该方法。问题是 $('#some-div-container').html(template(someJsonObject));
行的方法似乎不起作用。
我显然在这里遗漏了一些东西。非常感谢!
Handlebars 不处理数据绑定以更新值更改。您可以使用像 ember 这样的框架,它带有双向数据绑定。
一种在数据更改时执行重新渲染的普通方法是使用 Object.observe:
Object.observe(someJsonObject, function() { template(someJsonObject); });
我有一个模板,它显示了一个基于 JSON 对象中的某个布尔值的按钮。它可以显示两个不同的按钮。
模板编译代码:
source = $('#some-template').html(); // Get the HTML source of the template
template = Handlebars.compile(source); // Compile it
$('#some-div-container').html(template(someJsonObject));
假设对象看起来像这样:
someJsonObject = {
smeBooleanValue : false,
someOtherValue : 5
};
模板如下所示:
<div id="some-div-container">
<script id="some-template" type="text/x-handlebars-template">
<button type="button" class="btn btn-default btn-lg" onclick="myGreatMethodForDoingThings()">
{{#if smeBooleanValue}} <span class="glyphicon glyphicon-stop" aria-hidden="true"></span> Do something
{{else}} <span class="glyphicon glyphicon-play" aria-hidden="true"></span> Do something else{{/if}}
</button>
</script>
</div>
问题是当 someJsonObject
中的布尔值发生变化时,视图不会更新。我以为这会自动发生(就像 Meteor 中的 Handlebars 一样),但我似乎错了?
在那种情况下:它是如何完成的?我可以有一个重新呈现模板的方法,可以在 setter 中为值调用该方法。问题是 $('#some-div-container').html(template(someJsonObject));
行的方法似乎不起作用。
我显然在这里遗漏了一些东西。非常感谢!
Handlebars 不处理数据绑定以更新值更改。您可以使用像 ember 这样的框架,它带有双向数据绑定。
一种在数据更改时执行重新渲染的普通方法是使用 Object.observe:
Object.observe(someJsonObject, function() { template(someJsonObject); });