google maps - The simpliest way to subscribe for an observableArray in knockoutjs -
i have observablearray markers, example:
var markers = ko.observablearray([ { id: 0, title: ko.observable("marker 0"), lat: ko.observable(55.31), lng: ko.observable(11) }, { id: 1, title: ko.observable("marker 1"), lat: ko.observable(57.20), lng: ko.observable(15.5) } ]); this array sent mapwidget object, has create google map markers each element. has move markers in case lat,lng observables change, change marker's title in case title observable changes , on.
that means in mapwidget there's array of googlemap markers, , should connected given observablearray. best , simpliest way connect them?
upd. more details mapwidget.
mapwidget object has access google maps map object, , receives argument observablearray markers 1 above.
var mapwidget = function(markers) { var div = $("#map").get(0); this.map = new gmaps.map(div); /* magic goes here: markers observablearray, subscribe it's changes, create gmaps.marker each new element, destroy in case of destroying them array, move , rename each marker in case of corresponding changes */ }
you subscribe array this:
ar.subscribe(function() { // clean , redraw markers }); if that, receive notification when item added/removed to/from array. not when property of item modified.
if want update google maps markers based on individual property changes in items, implement simple dirty flag mechanism , subscribe individually each item. since each item has id, presume unique, create map key/value pairs being id , map widget.
so, given each individual item:
var item = function(data) { var self = this; self.ischanged = ko.observable(self); self.id = data.id; self.title = ko.observable(data.title); self.title.subscribe(function() { self.ischanged(self); self.ischanged.valuehasmutated(); }); self.lat = ko.observable(data.lat); self.lat.subscribe(function() { self.ischanged(self); self.ischanged.valuehasmutated(); }); self.lng = ko.observable(data.lng); self.lng.subscribe(function() { self.ischanged(self); self.ischanged.valuehasmutated(); }); } and given hypothetic map keep link between markers , items:
var markersmap = []; markersmap[0] = yourgooglemapwidget; you can subscribe track changes on items this:
ar[0].ischanged.subscribe(function(item) { var mygmapmarker = markersmap[item.id()]; // update marker, or destroy , recreate it... });
Comments
Post a Comment