Adding AJAX Loader to Model

This is for adding a reusable function that supports an Ajax animation loader.

Table of Contents

 

Technologies

It uses the following frameworks and technologies:

  • MVC.net & Razor
  • RequireJs
  • KnockoutJs
  • Html/CSS

 

The animation automatically shows or hides. It does this by watching the jQuery ajax events and updating the state.loading observable.

The partial razor page binds to the loading state.

 

 

AjaxModelExtender.js

define(["jQuery", "knockout"], function($, ko) {
    return {extend: function(model) {
            /* Ajax UI animation handling */
            model.state = model.state || {};
            model.state.loading = ko.observable(false);
            $(document).on({
                ajaxStart: function() {
                    model.state.loading(true);
                },
                ajaxStop: function() {
                    model.state.loading(false);
                },
                ajaxError: function() {
                    model.state.loading(false);
                }
            });
        }
    };
});

 

app.js / main.js

define(["app.model", "app.ui", "app.data", "ajaxModelExtender"], function (model, ui, data, ajaxModelExtender) {
    var app = {};
    app.model = model;
	app.data = data;
	app.ui = ui;
    ajaxModelExtender.extend(model); //This is the usage for the extender
	...    
	return app;
});

 

Partial Page (Razor)

<div data-bind="visible: state.loading, if: state.loading, click: function(){state.loading(false)}" class="spin" style="display: none;
                                      white-space: nowrap;">
    <img id="spinner" src="@Url.Content("~/Content/img/ajax-loader.gif")" />
    Please wait...
</div>

CSS

.spin img {
    vertical-align: middle;
}
.spin
{
    padding: 30px;
    border: 1px solid #addaff;
    vertical-align: middle;
    background-color: #ffffff;
    text-align: center;
    position: fixed;
    left: 50%;
    top: 45%;
    margin-left: -75px;
    margin-top: -50px;
    z-index: 999;
}

 

Image

ajax-loader.gif

Location: ~/Content/img/ajax-loader.gif

 

CodeMonkey Software is a division of JCHMedia www.jchmedia.com