I am using backbone for persistence and knockout for binding, i.e. I am using knockback On page load, all is well. When I click on the check box, based on the value of IsChecked, either yes or no is displayed.
When I click on reset model button, the previously seen behavior is lost. That is, if 'yes' is being displayed and I click on reset, then 'no' will never be displayed no matter the check box state.
If I use visible binding it will work but I need to get this 'if' to work so that I can decide whether to render some form elements depending on user criteria.
Any help is appreciated. Thanks.
Here is my sample code:
<script type="text/javascript">
var model_a;
var collection_ac;
var example_new_model_a;
$(document).ready(function () {
model_a = Backbone.Model.extend({
idAttribute: 'A_Pid',
defaults: {
A_Pid: null,
ChildName: "",
IsChecked: false,
Show: false,
},
});
example_new_model_a = new model_a();
example_new_model_a.set('ChildName', 'child of test');
vm = kb.viewModel(example_new_model_a);
ko.applyBindings(vm, $('#div1')[0]);
});
var vm;
function reset_model() {
kb.utils.release(vm);
vm = null;
example_new_model_a = new model_a();
example_new_model_a.set('ChildName', 'child of test2');
vm = kb.viewModel(example_new_model_a);
ko.applyBindings(vm, $('#div1')[0]);
}
function show_div() {
example_new_model_a.set('Show', true);
}
<div id="div1">
<div data-bind="visible: Show">
Check or Uncheck <input type="checkbox" data-bind="checked: IsChecked" />
<!-- ko if:IsChecked -->
<p>yes</p>
<!-- /ko -->
<!-- ko if:!IsChecked() -->
<p>no</p>
<!-- /ko -->
<button data-bind="click: reset_model">Reset</button>
</div>
<button data-bind="click: show_div">Show</button>
Edit
I found that if I add the following code, even after pressing reset, it works. After reading How to force a view refresh without having it trigger automatically from an observable? and Knockout.js Templates Foreach - force complete re-render, I tried the template with if and it works. Not sure how to call value has mutated from knockback view model so unless there is a better way, I will use this workaround.
<div data-bind="template: { name: 'test-template-1', if:IsChecked}"></div>
<script type="text/html" id="test-template-1">
<p>yes2</p>
</script>
<div data-bind="template: { name: 'test-template-2', if:!IsChecked()}"></div>
<script type="text/html" id="test-template-2">
<p>no2</p>
</script>