I’m using the mapping plugin to create my client side view model based on an object that gets sent from the server. The object is basic address information ie: address1, address2, city, state, postal, ect…
Once the view model is bound, I want a google maps canvas to update if the user changes the address. I created a computed observable that checks the values entered and calls a map update function. I had this working before when I wasn’t using the mapping plugin, ie model was defined locally, but once I introduced mapping I wasn’t able to append the computed observable to the view model.
I tried following the instructions from the mapping plugin documentation, but the computed observable isn’t triggering updates. I have a custom mapping that calls a mapModel which contains the computed observable as in the examples, but no updates.
Any ideas?
$.getJSON("@Url.RouteUrl("
ContactUs_default ", new { action = "
GetPageModel ", Model.BusinessID})", function(result) {
//create map property
result.Data.Map = null;
var mapping = {
'Map': {
create: function(options) {
return new mapModel(options.data);
}
}
};
var viewModel = ko.mapping.fromJS(result.Data, mapping);
ko.applyBindings(viewModel);
});
var mapModel = function(data) {
ko.mapping.fromJS(data, {}, this);
this.Map = ko.computed(function() {
var address = "";
var enteredElements = 0;
if (this.Address1 != helpText) {
address += " " + this.Address1;
enteredElements++;
}
if (this.Address2 != helpText) {
address += " " + this.Address2;
}
if (this.City != helpText) {
address += " " + this.City;
enteredElements++;
}
if (this.State != helpText) {
address += " " + this.County;
enteredElements++;
}
if (this.PostalCode != helpText) {
address += " " + this.Postal;
}
alert("hi");
//only upate map if enough data has been entered to give accruate location
if (enteredElements >= 3) {
MYMAP.placeMarkers(address);
}
}, this);
};
When you send your data through the mapping plugin, all of your properties will become observables.
This means that you need to access them as a function like like:
When you access them as observables inside of a computed observables, then it will create a dependency. So, currently your computed observable would get initially evaluated, but it would never update again, as it does not access the value of any observables.