Skip to content

Server Utilities

jstrimpel edited this page Sep 18, 2014 · 2 revisions

Lazo provides the ability to create utility end points that accept GET and POST requests. This functionality is useful for implementing features like file uploading.

The crumb is required when POSTing.

Creating a Server Utility

Placing an AMD module named utilActions.js inside of a component_name/server or app/server directory creates a server utility. This module should return an object with at least one method that is responsible for responding to a server request. Each method should accept two arguments. The first is the request object itself and the second is the standard options object with success and error callbacks.

// app/server/utilActions.js
define(function () {

    'use strict';

    return {

        mood: function (request, options) {
            options.success({
                mood: 'I am really, really happy.'
            });
        }

    };

});

Accessing a Server Utility from the Client

Server utilities can be access from the client by making an AJAX POST or GET request to server utility method.

define(['lazoView'], function (LazoView) {

    'use strict';

    return LazoView.extend({

        events: {
            'click button': 'getMood'
        },

        getMood: function (e) {
            var self = this;
            e.preventDefault();

            $.ajax({
                type: 'GET',
                // resolves to 'app/server/utilActions.js', mood method
                // to resolve to a component server utility action the
                // path would be /fn/component_name/method_name, which
                // would resolve to component_name/server/utilActions.js,
                // method_name
                url: '/fn/mood',
                success: function (resp) {
                    self.$('.mood').html(resp.mood);
                }
            });

        }

    });

});