I am using maps and backbone.js together. Map JS library used is Leaflet, but Google maps API will apply here as well.
Problem: Backbone.js allows us to seperate the presentation (Views) from the data (Models, Collections). When using Google Maps JS API or Leaflets, we do not seem to have control over the rendering of the markers, thus unable to have a Backbone View for each marker. Is this true?
When using Maps together with backbone.js, I start to get nested views and event handlers in the callback functions.
JS (Leaflet, similar to Google Maps API)
// Handle a dragging on the map
map.on('dragend', function() {
App.markersList.fetch(
data: someData,
processData: true
function() {
App.markersListView.render();
};)
});
// Handle a click on a Marker
map.on('popupopen', function() {
// Activate bootstrap tabs
$('#tabs').tab();
// Submit click handler
$('#submit-button').click(function() {
$.post('/api/submit-something',
{data: data},
function() {
// Remove some divs
$('#some-divs').fadeOut();
})
})
// Activate slideshow
Galleria.loadTheme('/js/vendor/galleria.miniml.min.js');
Galleria.configure({
height: 320
});
Galleria.run('#galleria');
// Validation
$('.email-link form').validate({
rules: { ... }
});
});
Well you get the idea… I need to do these outside of Backbone’s MVC structure. I could be missing out on the correct way to integrate both together. Any ideas? Thanks!!
I guess with view for the marker you mean the content of a popup to that marker? It is possible to bind a view as the popup content of a feature. At least in Leaflet that is.
The key is, that Leaflet Popups allow to use a provided DOM element as its content. To have appropriate knowledge of the model behind a marker you may specify the marker as a property of the model. This allows you to get the associated marker of the model. The other way around can be achieved via an event binding to the marker whose signature comprises the model.
This is a simplified snippet of my map view how to to set it up after fetching the collection:
Here, for each model in the collection a marker is drawn and then the marker becomes a property of the model. Also, each marker is bound with an click event that triggers the custom “model:select” event on an application-wide event aggregator. From here on you can use that event to set up the popup view by catching the event like:
InitPopup may look like this:
The PopupView is a Backbone view (Well, Marionette in my case.) complete with template and event handling and so on.