How can I get a leaflet.js instance using only a DOM object?
As long as you are sure that the DOM element will not be removed, you could just add it as a subproperty on the DOM element itself. Here's a binding handler using the code on the leaflet front page for setting up the leaflet map:
ko.bindingHandlers.leaflet = {
init: function(element, valueAccessor){
var map = L.map(element);
element.myMapProperty = map;
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
},
update: function(element, valueAccessor){
var existingMap = element.myMapProperty;
var value = ko.unwrap(valueAccessor());
var latitude = ko.unwrap(value.latitude);
var longitude = ko.unwrap(value.longitude);
var zoom = ko.unwrap(value.zoom);
existingMap.setView([latitude, longitude], zoom);
}
};
To use the binding handler you would just bind like the following:
<div data-bind="leaflet: { latitude: latitudeProperty, longitude: longitudeProperty, zoom: zoomProperty }"></div>
Just ensure that you have also styled the div
to ensure it has a height and width. I have written a jsfiddle which uses the above leaflet bindingHandler where you could try it out.
I have only tested this jsfiddle in Internet Explorer 11, Firefox 26.0 and Firefox 27.0.1.