Search code examples
jqueryajaxbackbone.js

AJAX requests in Backbone


Is there a way to avoid all the explicit AJAX requests $.ajax() I seem to have to make when using Backbone?

I use AJAX to get templates from the server and for all sorts of other things, it seems kinda ghetto.

if (this.template == null) {
    $.ajax({
        url: 'static/html/ejs/homeTemplate.ejs',
        type: 'GET',
        success: function(msg) {
            var ret = EJS.render(msg, {
                title: 'Welcome to the jungle',
                //filename: '/static/html/ejs/indexEJSTemplate.ejs'
            });
            self.$el.html(ret);
            //$('body').append(ret);
            console.log('HomeView rendered');
        },
        error: function(err) {
            console.log('error:', err);
        }
    });
} else {
    var ret = EJS.render(this.template, {
        title: 'Welcome to the jungle',
        //filename: '/static/html/ejs/indexEJSTemplate.ejs'
    });
    self.$el.html(ret);
    //$('body').append(ret);
    console.log('HomeView rendered');
}

Solution

  • Avoid AJAX calls for the following:

    1. Retrieving templates from the server
    2. Retrieving CSS from the server

    by using the text plugin for RequireJS:

    https://github.com/requirejs/text

    if you are not using RequireJS, there are surely similar tools for Angular, Webpack and Browserify, that can include templates/CSS and other text based files in your build, whether it's for development or production.