John Cheesman

Simple jQuery Data Binding

Code

An easy way to store and automatically update view data with custom jQuery events.

I came up with this for a project at work where we needed to conditionally show and hide form fields based on the values of other fields. I’d originally intended to use a framework like Angular that would have provided this functionality (and much more) but couldn’t justify the overhead for a simple form interface.

// Declare a global object to store view data.
var viewData;

viewData = {};

$(function() {
    // Update the viewData object with the current field keys and values.
    function updateViewData(key, value) {
        viewData[key] = value;
    }

    // Register all bindable elements
    function detectBindableElements() {
        var bindableEls;

        bindableEls = $('[data-bind]');

        // Add event handlers to update viewData and trigger callback event.
        bindableEls.on('change', function() {
            var $this;

            $this = $(this);

            updateViewData($this.data('bind'), $this.val());

            $(document).trigger('updateDisplay');
        });

        // Add a reference to each bindable element in viewData.
        bindableEls.each(function() {
            updateViewData($(this));
        });
    }

    // Trigger this event to manually update the list of bindable elements, useful when dynamically loading form fields.
    $(document).on('updateBindableElements', detectBindableElements);

    detectBindableElements();
});

Demo

Here’s an example that prints out the field values.

See the Pen Simple jQuery Data Binding by John Cheesman (@john-cheesman) on CodePen.