Reputation: 1618
Using Knockout, is it possible to set up one-way binding such that changing the view model will update the view, but updating the view won't update the view model?
I am using a routing engine to get parameters from the URL, to fetch data from a source, to populate a view model, to populate a form (view). But, I don't want to update the view model when the user changes the form values - I want them to "submit" the form, which will update the URL, which will trigger the routing engine...
I have tried data-bind="textInput: MyValue"
, which updates the view model per keystroke, data-bind="value: MyValue"
, which updates the view model when the form element loses focus, data-bind="attr: {value: MyValue}"
, which works for the initial bind, but then changing the view model's value does not update the view.
Are there any default bindings that will do what I want? Any other approaches?
Thanks!
Upvotes: 0
Views: 558
Reputation: 1567
If you execute a property in knockout binding is becomes a one way/read only. So in the following model for example:
var Person = function(data){
var self = this;
self.FirstName = ko.observable(data.FirstName);
self.LastName = ko.observable(data.LastName);
self.FullName = ko.computed(function(){
return self.FirstName() + " " + self.LastName()
});
}
myData = { FirstName: "John", LastName: "Smith" }
var me = new Person(myData);
ko.applyBindings(me);
I can make FirstName a one way/read only property simply by executing it in the binding:
<input data-bind="value: FirstName()">
<input data-bind="value: LastName">
<label data-bind="text: FullName"></label>
So now the first input only gets the value and can not set it but the second input will have two way binding and will update the LastName property.
Upvotes: 2