Search code examples
google-mapsknockout.jsknockout-componentsknockout-binding-handlers

Knockout Google Map: Component vs. Custom Binding Handler


When I google "Knockout Google Maps" I find quite some KO-based Google Maps implementations. All of which I was able to find take the approach to use a custom binding handler whereas I originally intended to implement it as a Knockout component.

Examples:

Can anyone point me in the right direction why one would prefer a custom binding handler over a KO component here?

My planned use case is this:

I'm implementing a page with a list of address search results. The list so far is a KO component, each list entry is generated by another KO component which the list component repeatedly calls in a foreach binding. Next to this list of search results I need a google map showing the result entries also in the map. There will also be quite a lot of interaction between the list, the list entries and the map.

Here's what I've got so far:

var GMap = function () {
    var self = this;

    var initMap = function() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 13,
            center: {lat: 51.4387974, lng: 6.9922915}
        });
    };
  
    initMap();
};
$(document).ready(function() {
  ko.components.register('gmap', {
    viewModel: GMap,
    template: { element: 'gmap' }
  });
  ko.applyBindings();
});
#map {
  height: 400px;
  width: 600px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.22"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<gmap></gmap>
<template id="gmap">
  <div id="map"></div>
</template>


Solution

  • A component and a custom handler are completely different things.

    Custom binding

    Basically a custom binding have access to:

    • the HTML component where it's used
    • the bound value (expression supplied to the binding)
    • all the other bindings in the element
    • the binding context of the element, from which you can acces to $root, $parent, and so on

    Its definition includes two functions:

    • init: that allows to do the initial setup, like initializing widgets, setting event handlers and so on
    • update: it's called after init. In that moment you can access properties (including observable properties) through the binding, all the element bindings, the context and so on. This creates subscriptios that will call update when any of the accessed observable changes.

    So a custom binding shuld be used when you need to interact directly with the DOM element, for example to modify its properties, initialize widgets, subscribe to events and so on

    Component

    A component is completely different. When you define a componente you must define:

    • a template, which is a set of DOM elements, usually with bindings
    • a viewmodel (usually a constructor or a factory)

    When you use the component:

    • the viewmodel is instanced
    • the template is loaded
    • the viewmodel is bound to the template

    So, a componente allows to reuse viewmodels and templates

    So, what's the difference?

    A custom binding has direct access to the DOM elements, allowing to interact with them, subscribe to events, modify properties, and so on

    A component is only a viewmodel, and a set of DOM elements with bindings to that particular viewmodel.

    So, in the case of Google Maps, which needs to initialize a widget (the map) and interact with Map events, and respond to observable propèrties cahnges, you could never use a component, because the component doesn't allow the direct interaction with the DOM elements. (Remember is a bunch of HTML elements with bindings, and the corrresponding view model, whic can't include any logic to intercat with those elements).

    A custom binding usually applies to a single element (althoug it could handle its children, like foreach). In the case of Google Maps you only need the element in which you'll show the map.

    A component is usually a more or less complex set of DOM elements, which are not accesible "from the outside". The only communication with the main viewmodel is done through parameters. The component cannot directly interact with the DOM elements: it must do it via ko bindings.

    So, for the case of Google Maps is clear that you need a custom binding.

    It only makes sense to create a component when you want to modularize or reuse a set of DOM elements, and the related viewmodel, which can also include functionality like accessing web services (via AJAX), making computations (propbaly by using computed observables), and so on. For example, a shopping cart could be implemented using a component, which would include:

    • the DOM elements to show the items in the cart (probably an HTML table, and some controls)
    • controls to modify the cart content (for example for deleting elements, or changing quantities)
    • a viewmodel that show the total, the taxes and so on
    • functionality to store the cart for later, or pay for it (which could be ajax calls to services)

    In this case the cart would have a viewmodel which would include the computed observables (to show the total and taxes), the functionality to remove items, or modify quantities, or store or pay, and so on. And a concrete set of DOM elements with bindings for this viewmodel, i.e. the HTML to show the cart and interact with it.

    In the case of Google Maps a component could not be used without the help of a custom binding or with the hacky use of additional, non ko, scripts.

    If you wanted to show a list of places beside a map, and modify that list, you could use a component, which would include a viewmodel with the list and related functionality, and a template including an element with the Google Maps custom binding. That would make sense: viewmodel + several elements.

    Conclusion

    This all means that a custom binding usually have a deep interaction with the bound DOM element, while a component has a higher level interaction with the elements, which must be done through bindings.

    So, they play a role at a very different level. You cannot compare or interchange them.

    If you insist on doing so, you could create a beast of a binding which behaves like a component, becasue you have full control on the elements, and full acces to the view model, but that's harder to implement than a component. And probably could do the other way round also in some esoteric way.