Reputation: 1057
I have a page where i have a Editable View through form elements, they are observables on key-down, the View is connected to two live preview on the same page.
When i initially apply bindings with sample data, all three areas - the form, two live preview areas get loaded up with sample data
<div id="create">
<!--Contains form elements-->
<form>
<!--Data Should not load during inital page load, empty textboxes should be shown to user. When user clicks on this text box, This values should be connected to two previews, replacing the sample data already binded
--> <input type="text" data-bind="value: jw_fullname, valueUpdate: 'afterkeydown'" placeholder="Full Name" id="jw_fullname" />
</form>
</div>
<div id="preview1">
Template One
<h1 id="title" data-bind="text: jw_fullname">
Sample data loaded here during page load
</h1>
</div>
<div id="preview2">
Template two
<p data-bind="text: jw_fullname"></p>
Sample data loaded here during page load
</div>
But i require only two previews to be loaded with sample data, Not the form elements, The elements should be empty during initial binding, when user clicks on the form element first name, whatever the user types in should be binded to both preview's replacing the sample data that is already loaded.
I am trying with
ko.applyBindings(my.vm.sample, document.getElementById('preview1'));
ko.applyBindings(my.vm.sample, document.getElementById('preview2'));
ko.applyBindings(my.vm.emptydataset, document.getElementById('create'));
But i can't connect those, How to connect the user input to reflect in both previews?
However when i just use
ko.applyBindings(my.vm)
All three are in sync with each other, they work right. But i don't want the user to delete the sample data on the form.
Upvotes: 1
Views: 139
Reputation: 1891
You can achieve this using a custom binding
Html:
<input type="text" data-bind="value: jw_fullname, valueUpdate: 'afterkeydown', emptyInit: emptyInit" placeholder="Full Name" id="jw_fullname" />
Javascript:
ko.bindingHandlers.emptyInit = {
init: function(element, valueAccessor, allBindingsAccessor,
viewModel, bindingContext)
{
element.value = '';
}
}
var ViewModel = function() {
this.jw_fullname = ko.observable("A");
this.emptyInit = ko.observable(true);
};
ko.applyBindings(new ViewModel());
And the fiddle of it
Upvotes: 1