Brainstorm's snippets (1/226)

  Javascript Module Pattern example

{% block extrajs %}
    <script type="text/javascript">

        // Setup task poller
        DeviceAdmin.CommandPoller.init(
            "{% url 'api:device' %}",
            {{config.UI_REFRESH_INTERVAL}}
        );

        ...

        DeviceAdmin.CommandPoller.sendCommandToDevice(channel, command, [cycle_command, [pipeIndex]]);

        ...

    </script>
{% endblock extrajs %}

where:

'use strict';


$(document).ready(function($) {
    $("#device_command_result").on('click', function() {
        console.log('click');
        DeviceAdmin.CommandPoller.step(0);
    });
});


// Module
window.DeviceAdmin = {};

// Poller initializations and functions
window.DeviceAdmin.CommandPoller = (function() {

    var _url_device_api = '';
    var _pending_command_id = 0;

    function init(url_device_api, autorepeat_interval) {
        _url_device_api = url_device_api;
        step(autorepeat_interval);
    };

    function step(autorepeat_interval) {
        checkPendingCommand();

        // Call again ourself after specified interval
        if (autorepeat_interval > 0) {
            setTimeout(function() {
                step(autorepeat_interval);
            }, autorepeat_interval);
        }
    };

    function sendCommandToDevice(channel, command, params) {
        ...
    }

    function checkPendingCommand() {
        ...
    }

    return {
        init: init,
        step: step,
        sendCommandToDevice: sendCommandToDevice
    };

})();

Same js code with more details

'use strict';


$(document).ready(function($) {
    $("#device_command_result").on('click', function() {
        console.log('click');
        DeviceAdmin.CommandPoller.step(0);
    });
});


// Module
window.DeviceAdmin = {};

// Poller initializations and functions
window.DeviceAdmin.CommandPoller = (function() {

    var _url_device_api = '';
    var _pending_command_id = 0;

    function init(url_device_api, autorepeat_interval) {
        _url_device_api = url_device_api;
        step(autorepeat_interval);
    };

    function step(autorepeat_interval) {
        checkPendingCommand();

        // Call again ourself after specified interval
        if (autorepeat_interval > 0) {
            setTimeout(function() {
                step(autorepeat_interval);
            }, autorepeat_interval);
        }
    };

    function sendCommandToDevice(channel, command, params) {

        setResult('pending');

        _pending_command_details = {
            channel: channel,
            command: command,
            params: params
        };

        $.ajax({
            type: "POST",
            url: _url_device_api,
            data: JSON.stringify(_pending_command_details),
            dataType: 'json',
            headers: {"X-CSRFToken": getCookie('csrftoken')}
        }).done(function(response_data) {
            var msg_id = response_data.data;
            console.log('msg_id: %d', msg_id);
            _pending_command_id = msg_id;
            //notifyUser('info', sprintf('"%s" sent to "%s"', command, channel));
        }).fail(function(jqXHR, textStatus) {
            console.log('FAILURE: %o', jqXHR);
            try {
                var obj = JSON.parse(jqXHR.responseText);
                notifyUser('error', obj.message);
            }
            catch (err) {
                notifyUser('error', jqXHR.responseText);
            }
        });

    }
    function checkPendingCommand() {
        if (_pending_command_id > 0) {
            // Check pending command completion
            var url = _url_device_api.replace('/0/', sprintf('/%d/', _pending_command_id));
            $.ajax({
                type: 'GET',
                url: url,
                dataType: 'json'
            }).done(function(response_data, textStatus, jqXHR) {
                // Here we treat any error as "no response yet"
                try {
                    if (response_data.result == 'success') {
                        var status = response_data.data.status;
                        if (status == STATUS_SUCCESS) {
                            _pending_command_id = 0;
                            setResult('success');
                        }
                        else if (status == STATUS_FAILURE) {
                            setResult('failure');
                            notifyUser('error', sprintf('%s command "%s" (%d) failed with error code %d',
                                _pending_command_details.channel,
                                _pending_command_details.command,
                                _pending_command_id,
                                response_data.data.status_code
                            ));
                            _pending_command_id = 0;
                        }
                    }
                }
                catch (err) {
                }
            }).fail(function(jqXHR, textStatus, errorThrown) {
                console.log('ERROR: %o', jqXHR);
                console.log('textStatus: %o', textStatus);
            });
        }
    }
    return {
        init: init,
        step: step,
        sendCommandToDevice: sendCommandToDevice
    };

})();