数据更改时重新呈现Handlebars模板

时间:2015-06-22 08:36:55

标签: jquery handlebars.js

我有一个模板,显示一个基于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));的方法不起作用。

我在这里显然遗漏了一些东西。非常感谢提前!

1 个答案:

答案 0 :(得分:1)

Handlebars不处理数据绑定以更新值更改。您可以使用类似ember的框架,它带有双向数据绑定。

在数据更改时执行重新呈现的一种方法是使用Object.observe

Object.observe(someJsonObject, function() { template(someJsonObject); });