Hiding empty elements on page load, but not afterwards using knockout.js - javascript

I have a form with a lot of inputs.
I am using the following syntax within my form: <!-- ko if: PropertyName -->. I am using this statement in the form for specific fields. This allows me to hide values that are not defined (actually not hide, but remove from DOM).
However, I do not need to hide them on the fly. I mean, when value was not empty and was loaded, then user can edit it, and user can empty it. In this case input disappears, I do not need this.
Can you suggest me – how to change my markup and what binding to use?
<!-- ko if: IsEmptyOnLoad(Property1) -->.
<input type="text" data-bind="value: Property1" />
<!-- /ko -->
<!-- ko if: IsEmptyOnLoad (Property2) -->.
<input type="text" data-bind="value: Property2" />
<!-- /ko -->
var myModel = function() {
var self = this;
self.Property1= ko.observable("non-empty");
self.Property2= ko.observable();
//self.IsEmptyOnLoad is not implemented, how to implement?
};
var m = new myModel();
ko.applyBindings(m);
You can try playing with the corresponding JSFiddle.
It could be strange, but I really have business scenario:
onload do not show any empty variables, so after page is loaded there would be only non-empty variables loaded into the page
after page is loaded, user can edit variables, some of those variables can be removed (become empty), but in this case I do not need to hide empty variables

Just create custom binding with empty update method. You can do whatever you want at binding init on page load (at knockout binding apply to be more specific).
ko.bindingHandlers.ifOnce = {
init: function(element, valueAccessor) {
var observable = valueAccessor(); // get observable
var value = observable(); // get value of observable
var isEmpty = !value; // do whatever check you want
// and remove element from dom if empty
if (isEmpty) {
element.parentNode.removeChild(element);
}
},
update: function(element, valueAccessor) {
// do nothing on update
}
};
Working example:
http://jsfiddle.net/2FTEM/6/
Lets go one step further. You asked how to create IsEmptyOnLoad. You can do this by using Knockout virtual elements and some useful methods they have. I.e.: ko.virtualElements.emptyNode will remove everything between Knockout <!-- ko --> tags http://knockoutjs.com/documentation/custom-bindings-for-virtual-elements.html
ko.bindingHandlers.IsEmptyOnLoad = {
init: function(element, valueAccessor) {
var observable = valueAccessor(); // get observable
var value = observable(); // get value of observable
var isEmpty = !value; // do whatever check you want
// and remove element from dom if empty
if (isEmpty) {
ko.virtualElements.emptyNode(element);
}
},
update: function(element, valueAccessor) {
// do nothing on update
}
};
ko.virtualElements.allowedBindings.IsEmptyOnLoad = true;
Working example: http://jsfiddle.net/2FTEM/7/

An interesting problem that has so far generated some inventive answers. It's a common trend that people seem to have a phobia of putting logic into the view-model. As the name suggests, it should be designed as an interface between the view and the model. Firstly, I would re-factor the view-model, something like this;
var myModel = function() {
var self = this;
var property = function (content, availibility) {
return {
content: ko.observable(content),
availibility: availibility
};
}
self.Property1 = property('non-empty', true);
self.Property2 = property();
};
Now your HTML can be simple;
<input type="text" data-bind="visible: Property1.availibility, value: Property1.content" />
<input type="text" data-bind="visible: Property2.availibility, value: Property2.content" />
I've also provided a fork of the JSFiddle for your reference
UPDATE: Re-factored for simplicity and minimal repetition.

Do you simply want to disable the additional field if the FirstName is empty? I can't see how hiding the first input field, as you are currently doing, will work as it will not allow anyone to enter a name once it disappears.
If you want to disable additional fields and leave the first filed you can use data-bind with disable to do the following and remove your <!-- ko if: .... --> statements:
<input type="text" data-bind="value: FirstName" />
<input type="text" data-bind="disable: FirstName().length === 0" />
See updated fiddle: http://jsfiddle.net/2FTEM/1/
UPDATE
You can set up an observable that updates once your view model is loaded: IsPageLoaded that you set to true. I've added a delay in the JS so you should see the control appear after the final lines update the observable: m.IsPageLoaded(true);. You may have to check this with your code to see if it works (without the setTimeout).
HTML:
<!-- ko if: IsNotEmpty -->.
<input type="text" data-bind="value: IsNotEmpty" />
<!-- /ko -->
<!-- ko if: IsEmpty && IsPageLoaded -->.
<input type="text" data-bind="value: ''" />
<!-- /ko -->
JS:
var myModel = function() {
var self = this;
self.IsPageLoaded = ko.observable(false);
self.IsNotEmpty = ko.observable("non-empty");
self.IsEmpty = ko.observable(true);
};
var m = new myModel();
ko.applyBindings(m);
// remove this timeout to test in your enviroment - just introduces a delay
setTimeout(function() {
m.IsPageLoaded(true);
}, 1000);
// simply use
// m.IsPageLoaded(true);
Updated Fiddle: http://jsfiddle.net/2FTEM/4/

Keep two copies of your model around: the version as it was on load and the version that's currently being edited.
var m = { onload : new myModel(),
current : new myModel() };
ko.applyBindings(m);
When binding, bind the visibility to the state on load and the editable value to the current state:
<!-- ko if: onload.Property1 -->.
<input type="text"
data-bind="value: current.Property1" />
<!-- /ko -->
http://jsfiddle.net/92GzK/

You can create normal variables (instead of observables) that are only used in the "if" statements. This way, the condition within the "if" won't get updated if you update the field :
self.Property1 = ko.observable("non-empty");
self.Property2 = ko.observable();
self.initialValue1 = self.Property1();
self.initialValue2 = self.Property2();
and the bindings are :
<!-- ko if: initialValue1 -->.
<input type="text" data-bind="value: Property1" />
<!-- /ko -->
<!-- ko if: initialValue2 -->.
<input type="text" data-bind="value: Property2" />
<!-- /ko -->
fiddle here : http://jsfiddle.net/2FTEM/13/
Hope that helps

Related

Make knockout listen to values changes which are not a result of a keystroke [duplicate]

This question already has an answer here:
Knockout.js bound input value not updated when I use jquery .val('xyz')
(1 answer)
Closed 6 years ago.
self.totalHours = ko.pureComputed(function() {
var start=self.num1;
var end=self.num2;
return start+end;
});
<input type="text" data-bind="textInput: start">
<input type="text" data-bind="textInput: end">
<input type="text" data-bind='text: totalHours()'>
The above first is part of my viewmodel and the second is part of my model. num1,num2 are observables. Every time I change manually the value inside the above first two inputs the third input is updated immediately; however, when the values change by code, knockout does not listen to the changes and total is not updated. How may I oblige knockout to listen to the changes provoked by code?
Quite some stuff you can fix and improve here:
A computed value will re-evaluate when an observable it uses in its method changes: self.num1 and/or self.num2 need to be observable and evaluated using ()
If you want to bind an <input>'s value, you have to use either the value or textInput data-bind; the text bind will not work.
If you want to write to a computed, you'll have to specify a write method. You'll have to tell knockout how to update the computed's dependencies to make sure all values add up. (e.g.: setting totalHours could set num1 to totalHours and num2 to 0)
You've bound to start and end, while your viewmodel properties are named num1 and num2.
When using value or textInput, user input will be returned as a string. You'll need to parse the strings to numbers if you want to use them in any math.
Now that all code should be working correctly, you can update your viewmodel's values via the inputs, or via code:
var ViewModel = function() {
var self = this;
self.num1 = ko.observable(0);
self.num2 = ko.observable(0);
self.totalHours = ko.pureComputed(function() {
var start = parseFloat(self.num1());
var end = parseFloat(self.num2());
return start + end;
});
};
var vm = new ViewModel();
ko.applyBindings(vm);
// Updating your values from code:
vm.num1(1);
vm.num2(2);
// Whenever the values need to be updated via js,
// you should change the source values, _not_ the
// <input>'s values. Worst case scenario, you'll
// have to do something like this:
var updateNum1ViaDOM = function() {
ko.dataFor(document.querySelector("input")).num1(5);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="textInput: num1">
<input type="text" data-bind="textInput: num2">
<span data-bind='text: totalHours'></span>
Note: it's probably better to use an extender to force num1 and num2 to be numeric: Live Example 1: Forcing input to be numeric
Not sure if it is a copy paste problem but the the code you posted will not work as intended. I've updated the example, when changing an observable value it must be passed as parameter so as not to overwrite the knockout observable
self.start = ko.observable();
self.end = ko.observable();
self.totalHours = ko.computed(function() {
return self.start() + self.end();
});
<input type="text" data-bind="textInput: start">
<input type="text" data-bind="textInput: end">
<input type="text" data-bind='text: totalHours()'>
//Then when changing the value by code
var newValue = 42;
model.start(newValue); //assuming you are making the change outside your viewmodel
*Just noticed this code will throw an exception when you edit the input bound to totalHours as it does not have a write handler defined. This is a separate issue though.

Radio buttons bound to knockout computed

I have some problems with knockoutjs writables computes observables I think.
I created a fiddle.
What I need is actually not so hard:
I have the nullable WeightInGramms and VolumeInMilliliters values.
These values should be bound to two input fields (only one of them should be visible).
At the top, the user can choose which of these values he want to use with the radio buttons.
At initialisation, when both of them are null, the "g" radio button should be checked, also when WeightInGramms is not null. When VolumeInMilliliters have some value, the "ml" radio button should be checked.
I used a knockoutjs writable computes observable for this, please correct me if there is a better way to do this!
So, the read function seems to work, when I change the value in the input which are bind to WeightInGramms or VolumeInMilliliters. But when I change the radio buttons nothing happens...
var ViewModel = function (data) {
var self = this;
this.VolumeInMilliliters = ko.observable(data.VolumeInMilliliters);
this.WeightInGramms = ko.observable(data.WeightInGramms);
this.GrammIsSelected = ko.computed({
read: function() {
return (!self.WeightInGramms() && !self.VolumeInMilliliters()) || !self.VolumeInMilliliters();
},
write: function (newValue) {
console.log(newValue);
return newValue;
},
owner: this
});
};
When I change the radio buttons, the corresponding input field should be visible:
<div data-bind="visible: GrammIsSelected">g is active</div>
<div data-bind="visible: !GrammIsSelected()">ml is active</div>
Edit:
When the Form is loaded for the first Time both values will be null -> the "g" button should be checked.
The observables can be initialized with:
null, null
33, null
null, 33
Both can be null, but only one of them can have a value.
If the user types in a value, and then clicks the other radio the value can be applied to the other value.
I hop it is a bit clearer
Some tips:
Make your viewModel (JS) resemble the view (HTML) as much as possible. Additionally, this avoids having to repeat too much markup. In this case, radio buttons are always lists, and so it is most convenient to store the options in an array.
Instead of testing whether GrammIsselected, you should define a selected observable that holds the selected metric. This way if you ever add more options, the code will still work without refactoring.
When to use a computed property? A computed property adds readonly value by calculating a result based on multiple observables/ variables. A writeable computed property does the same, except you can write back changes. This makes it especially useful for 'Select all' style checkboxes (see example 2 in the docs), data validation & transformations.
The absolutely clearest setup for what you want to achieve would be the following:
var ViewModel = function (data) {
this.metrics = [
{ name: 'g', value: ko.observable(data.WeightInGramms) },
{ name: 'ml', value: ko.observable(data.VolumeInMilliliters) }
];
this.selectedMetric = ko.observable(this.metrics[0]);
};
By setting an object as observable (selectedMetric), you can furthermore simplify the markup for the volume/weight input:
<div class="control-group">
<label class="control-label">choose</label>
<div class="controls" data-bind="with: selectedMetric">
<input type="text" data-bind="value: value">
<span class="help-inline" data-bind="text: '(' + name + ')'"></span>
</div>
</div>
Getting the 'final value' of your app would be as easy as retrieving selectedMetric().value().
A computed property isn't super useful here, but for example, if you wanted to provide a way for the user to both set the g/ml with radio buttons and text, you could add the following method to your viewModel:
this.selectedMetricByText = ko.computed({
read: function() {
return this.selectedMetric().name;
},
write: function(value) {
var newMetric = ko.utils.arrayFirst(this.metrics, function(metric) {
return metric.name === value;
}) || false;
this.selectedMetric(newMetric || this.metrics[0]);
}
}, this);
Fiddle
Your write function doesn't write anything, it seems?
Contrary to this other answer, based on my experience I'll give you the advice not to avoid writeable computeds: used wisely they can be very effective!
Note: in my answer I try to remain close to the original design from the question, but if you're able (have resources available) I recommend redesigning things even more based on the answer by #Tyblitz.
Here's the way you could approach this utilizing a computed:
var ViewModel = function (data) {
var self = this;
self.VolumeInMilliliters = ko.observable(data.VolumeInMilliliters);
self.WeightInGramms = ko.observable(data.WeightInGramms);
var _measurementType = ko.observable("volume");
self.MeasurementType = ko.computed({
read: function() {
return _measurementType();
},
write: function (newValue) {
_measurementType(newValue);
self.VolumeInMilliliters(newValue === "volume" ? 0 : null);
self.WeightInGramms(newValue === "mass" ? 0 : null);
}
});
};
ko.applyBindings(new ViewModel({ VolumeInMilliliters: 12 }));
label { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<label>
<input type="radio" name="measurementType" value="volume" data-bind="checked: MeasurementType">
Volume
</label>
<input data-bind="value: VolumeInMilliliters, enable: MeasurementType() === 'volume'">
<label>
<input type="radio" name="measurementType" value="mass" data-bind="checked: MeasurementType">
Weight in gramms
</label>
<input data-bind="value: WeightInGramms, enable: MeasurementType() === 'mass'">
For radio buttons, you need to use the "checked" binding.
http://knockoutjs.com/documentation/checked-binding.html
And for my personal experience (as a KO nija) I have to give you the advice: avoid writeable ko computed.
<input type="radio" name="unitSelector" value="g" data-bind="checked: unit" /> Grams</br>
<input type="radio" name="unitSelector" value="ml" data-bind="checked: unit" /> Millis</br>
Now the view model
var ViewModel = function (data) {
var self = this;
self.unit = ko.observable('g');
self.userValue = ko.observable(data.WeightInGramms);
};
Now the binding should only care about the value entered by the user, you don't need computed here and you don't need two fields...
<input type="text" data-bind="textInput: userValue ">
<span data-bind="text: unit"> </span>
It looks really too simple but that's what you need, as #Jotabe mentioned, you should take measurement and the unit as two separate things... what you do with this thing later, could be done with computed observables.
If this thing doesn't solve your problem then you should tell what you really want...

DataPicker not getting binded to textbox ? fiddle provided

Well in other cases i will get datepicker binded to my textbox which will be straight forward but not in this case .
Fiddle link : http://jsfiddle.net/JL26Z/1/ .. while to setup perfect seanrio i tried but unable to bind datepicker to textboxes . except that everything is in place
My code :
**<script id="Customisation" type="text/html">** // here i need to have text/html
<table style="width:1100px;height:40px;" align="center" >
<tr>
<input style="width:125px;height:auto;" class="txtBoxEffectiveDate" type="text" id="txtEffective" data-bind="" />
</tr>
</script>
The above code is used for my dynamic generation of same thing n no of time when i click each time on a button . So above thing is a TEMPLATE sort of thing .
My knockout code :
<div data-bind="template:{name:'Customisation', foreach:CustomisationList},visible:isVisible"></div>
<button data-bind="click:$root.CustomisatioAdd" >add </button>
I tried same old way to bind it with datepicker
$('#txtEffective').datepicker(); // in document.ready i placed
Actually to test this i created a textbox with some id outside script with text/html and binded datepicker to it and It is working fine sadly its not working for the textbox inside text/html and i want to work at any cost.
PS: well i haven't posted my view model as it is not required in this issue based senario
View model added with Js
var paymentsModel = function ()
{
function Customisation()
{
var self = this;
}
var self = this;
self.isVisible = ko.observable(false);
self.CustomisationList = ko.observableArray([new Customisation()]);
self.CustomisationRemove = function () {
self.CustomisationList.remove(this);
};
self.CustomisatioAdd = function () {
if (self.isVisible() === false)
{
self.isVisible(true);
}
else
{
self.CustomisationList.push(new Customisation());
}
};
}
$(document).ready(function()
{
$('#txtEffective').datepicker();
ko.applyBindings(new paymentsModel());
});
Any possible work around is appreciated
Regards
The best way I've found to do this is create a simple bindingHandler.
This is adapted from code I have locally, you may need to tweak it...
** code removed, see below **
Then update your template:
** code removed, see below **
By using a bindingHandler you don't need to try to hook this up later, it's done by knockout when it databinds.
Hope this is helpful.
EDIT
I created a fiddle, because I did indeed need to tweak the date picker binding quite a lot. Here's a link to the Fiddle, and here's the code with some notes. First up, the HTML:
<form id="employeeForm" name="employeeForm" method="POST">
<script id="PhoneTemplate" type="text/html">
<div>
<span>
<label>Country Code:</label>
<input type="text" data-bind="value: countryCode" />
</span>
<span><br/>
<label>Date:</label>
<input type="text" data-bind="datepicker: date" />
</span>
<span>
<label>Phone Number:</label>
<input type="text" data-bind="value: phoneNumber" />
</span>
<input type="button" value="Remove" data-bind="click: $parent.remove" />
</div>
</script>
<div>
<h2>Employee Phone Number</h2>
<div data-bind="template:{name:'PhoneTemplate', foreach:PhoneList}">
</div>
<div>
<input type="button" value="Add Another" data-bind="click: add" />
</div>
</div>
</form>
Note I removed the id=... from in your template; because your template repeats per phone number, and ids must be unique to be meaningful. Also, I removed the datepicker: binding from the country code and phone number elements, and added it only to the date field. Also - the syntax changed to "datepicker: ". If you need to specify date picker options, you would do it like this:
<input type="text" data-bind="datepicker: myObservable, datepickerOptions: { optionName: optionValue }" />
Where optionName and optionValue would come from the jQueryUI documentation for datepicker.
Now for the code and some notes:
// Adapted from this answer:
// https://stackoverflow.com/a/6613255/1634810
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {},
observable = valueAccessor(),
$el = $(element);
// Adapted from this answer:
// https://stackoverflow.com/a/8147201/1634810
options.onSelect = function () {
if (ko.isObservable(observable)) {
observable($el.datepicker('getDate'));
}
};
$el.datepicker(options);
// set the initial value
var value = ko.unwrap(valueAccessor());
if (value) {
$el.datepicker("setDate", value);
}
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$el.datepicker("destroy");
});
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
$el = $(element);
//handle date data coming via json from Microsoft
if (String(value).indexOf('/Date(') === 0) {
value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
}
var current = $el.datepicker("getDate");
if (value - current !== 0) {
$el.datepicker("setDate", value);
}
}
};
function Phone() {
var self = this;
self.countryCode = ko.observable('');
self.date = ko.observable('');
self.phoneNumber = ko.observable('');
}
function PhoneViewModel() {
var self = this;
self.PhoneList = ko.observableArray([new Phone()]);
self.remove = function () {
self.PhoneList.remove(this);
};
self.add = function () {
self.PhoneList.push(new Phone());
};
}
var phoneModel = new PhoneViewModel();
ko.applyBindings(phoneModel);
Note the very updated binding handler which was adapted from this answer for the binding, and this answer for handling onSelect.
I also included countryCode, date, and phoneNumber observables inside your Phone() object, and turned your model into a global variable phoneModel. From a debugger window (F12 in Chrome) you can type something like:
phoneModel.PhoneList()[0].date()
This will show you the current value of the date.
I notice that your form is set up to post somewhere. I would recommend instead that you add a click handler to a "Submit" button and post the values from your phoneModel using ajax.
Hope this edit helps.
Dynamic entities need to have datepicker applied after they are created. To do this I'd use an on-click function somewhere along the lines of
HTML
<!-- Note the id added here -->
<button data-bind="click:$root.CustomisatioAdd" id="addForm" >add </button>
<script>
$(document).on('click', '#addForm', function(){
$('[id$="txtEffective"]').datepicker();
});
</script>

Issue in getting index value

I am trying to store value in attribute in input tag which would like as follows.
The following code will repeat several times and the value for different radio can be saved using index.
<div data-bind="attr : { name : 'ex['+$index()+']' }>
<input type="radio" name="value" data-target="#modal" data-bind="click:fun.fill($index())"/>
</div>
From the above text box i can get the index of that input.And it points to a common modal function from bootstrap which opens a popup.
<div class="modal fade">
<select data-bind="attr:{name:'assignedResources['+$index()+'][repeatedType]'},
options : $root.repeats,value : repeatedType"></select>
</div><!-- /.modal -->
This is a sample of modal target.I want to call this modal as common.(i.e)it will be called from several places.I want to show appropriate popup for appropriate click from radio button.
But what i get is value of last index.Thats my problem
I'm not 100% sure I understand your question, but something like this...
this.abc = ko.observable('');
this.fun = {
var that = this;
fill: function(index) {
console.log(that.abc());
}
}
As far as I understand your problem, you need an observable to store your value, and then you can access it by any other function on your viewModel.
This is a jsFiddle with my initial approach, let me know if is what you needed or clarify instead:
http://jsfiddle.net/rdarioduarte/X8Rc4/
With a model like this:
var viewModel = function() {
this.abc = ko.observable('Value to store');
this.fun = function() {
alert(this.abc());
}
}
ko.applyBindings(new viewModel());
Thanks,
Dario
I do not quite understand about your question. But, maybe this may help:
1) Obtains index of your input element automatically on page load to viewModel function maybe need custom binding to handle that:
e.g custom binding:
ko.bindingHandlers.saveIndex = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var index = ko.utils.unwrapObservable(valueAccessor());
viewModel.fun(index); // accessing fun function on viewModel
// You can also access that function using bindingContext.$root
// bindingContext.$root.fun(index);
}
};
e.g html:
<input type="text" data-bind="saveIndex: $index()"/>
2) Store index to input value attribute using attr binding:
<input type="text" data-bind="attr: { value: $index() }">
3) Send your input attr value to viewModel function onClick:
<input type="text" value="thisIsExampleValue" data-bind="click: function() { $root.fun($element.value); }">
You also can use event binding for this behavior, Knockout.Event-binding
UPDATE:
Try this:
<div data-bind="attr : { name : 'ex['+$index()+']' }>
<input type="radio" name="value" data-target="#modal" data-bind="click: function() { fun.fill($index()) }"/>

How to create an observable array with undo?

I am trying to add knockout JS to a search page on our website. Currently you open up a jQuery dialog box, which has a number of checkboxes of criteria that you can select.
There are multiple dialogs with multiple types of criteria. When you open the dialog, the checkboxes do not take effect until you hit an "Update" button, if you click cancel or just close the window, the changes you made get reverted and the dialog is set to its former state.
I read this and a few other posts. However this seems to only work with ko.observable, and I cannot seem to get it to work with ko.observableArray.
Has anyone accomplished this or have any ideas?
An example of what I want to do:
Html:
<form>
<div>
<div>
<label><input type="checkbox" data-bind="checked: genders" value="1" />Male</label>
<label><input type="checkbox" data-bind="checked: genders" value="2" />Female</label>
</div>
</div>
<a id="buttonCancel">Cancel</a>
<a id="buttonUpdate">Update</a>
</form>
<div data-bind="text: ko.toJSON(viewModel)"></div>
Javascript:
var viewModel = {
genders: ko.observableArrayWithUndo([])
};
ko.applyBindings(viewModel);
$('#buttonCancel').click(function(){
viewModel.genders.resetChange();
});
$('#buttonUpdate').click(function(){
viewModel.genders.commit();
return false;
});
Here would be one way to approach it:
//wrapper to an observableArray of primitive types that has commit/reset
ko.observableArrayWithUndo = function(initialArray) {
var _tempValue = ko.observableArray(initialArray.slice(0)),
result = ko.observableArray(initialArray);
//expose temp value for binding
result.temp = _tempValue;
//commit temp value
result.commit = function() {
result(_tempValue.slice(0));
};
//reset temp value
result.reset = function() {
_tempValue(result.slice(0));
};
return result;
};
You would bind your checkboxes to yourName.temp and the other part of your UI to just yourName.
Here is a sample: http://jsfiddle.net/rniemeyer/YrfyW/
The slice(0) is one way to get a shallow copy of an array (or even just slice()). Otherwise, you would be performing operations on a reference to the same array.
Given HTML similar to:
<div>
<button data-bind="click: function() { undo(); }">Undo</button>
<input data-bind="value: firstName" />
<input data-bind="value: lastName" />
<textarea data-bind="value: text"></textarea>
</div>
You could use some Knockout code similar to this, basically saving the undo stack as a JSON string representation of the state after every change. Basically you create a fake dependent observable to subscribe to all the properties in the view, alternatively you could manually iterate and subscribe to each property.
//current state would probably come from the server, hard coded here for example
var currentState = JSON.stringify({
firstName: 'Paul',
lastName: 'Tyng',
text: 'Text'
})
, undoStack = [] //this represents all the previous states of the data in JSON format
, performingUndo = false //flag indicating in the middle of an undo, to skip pushing to undoStack when resetting properties
, viewModel = ko.mapping.fromJSON(currentState); //enriching of state with observables
//this creates a dependent observable subscribed to all observables
//in the view (toJS is just a shorthand to traverse all the properties)
//the dependent observable is then subscribed to for pushing state history
ko.dependentObservable(function() {
ko.toJS(viewModel); //subscribe to all properties
}, viewModel).subscribe(function() {
if(!performingUndo) {
undoStack.push(currentState);
currentState = ko.mapping.toJSON(viewModel);
}
});
//pops state history from undoStack, if its the first entry, just retrieve it
window.undo = function() {
performingUndo = true;
if(undoStack.length > 1)
{
currentState = undoStack.pop();
ko.mapping.fromJSON(currentState, {}, viewModel);
}
else {
currentState = undoStack[0];
ko.mapping.fromJSON(undoStack[0], {}, viewModel);
}
performingUndo = false;
};
ko.applyBindings(viewModel);
I have a sample of N-Level undo with knockout here:
http://jsfiddle.net/paultyng/TmvCs/22/
You may be able to adapt for your uses.

Categories