问题
I'm trying to create a modal window used to get values from the user to send off to a server. I want to prepopulate the fields with the values that we currently have, and have them update with the current values (stored locally) when the modal window appears.
The issue I'm running into is that when I link the fields to the observable directly, the user will edit the fields and if they hit 'Cancel', the values the previous screen shows will contain the updated values. If I bind it like "value: (), I get a string that can be edited but if the user were to open it, edit the value, close it, then reopen it... the edited changes are still there.
Does anyone have advice on how to get updated information for the form without having to link directly to the observable? Is there a way to refresh these bindings when I make the call to open this window?
A sample of my current form is below.
<form>
...
<div class="control-group">
<label class="control-label" >Cellular Fault Time (in Minutes)</label>
<div class="controls">
<input type="text" class="input-small" id="gsmfaultecptime" maxlength="2" onkeypress='return isNumberKey(event)'
data-bind="value: gsmfaulttime()">
</div>
</div>
<div class="control-group">
<label class="control-label" >Cellular IP1</label>
<div class="controls">
<input type="text" readonly class="input-medium" data-bind="value: csip()">
</div>
</div>
...
</form>
回答1:
I have used two approaches in the past to handle revertable data elements.
Have a view model dedicated to the modal that is replaced each time it is opened.
launchModal: function () { $('#dialog').dialog('open') var obs = this.obs; var dialogViewModel = { anotherObs: ko.observable(obs()), accept: function () { obs(dialogViewModel.anotherObs()) $('#dialog').dialog('close') }, cancel: function () { $('#dialog').dialog('close') } } ko.applyBindings(dialogViewModel, $('#dialog')[0]) }Decorate the observable to provide modification handling.
self.createSpecialObservable = function () { var obs = ko.observable("Greetings") obs.originalValue = undefined; obs.revert = function () { if (obs.originalValue) { obs(obs.originalValue) obs.originalValue = undefined; } } obs.accept = function(){obs.originalValue = undefined} obs.subscribe(function (newValue) { if (!obs.originalValue) { obs.originalValue = obs(); } }, null, "beforeChange") return obs; }Both usages are available in this example
Edit: See also this example.
来源:https://stackoverflow.com/questions/21486214/how-do-i-show-a-knockout-observable-value-in-an-editable-field-without-changing