Chaddeus
Chaddeus

Reputation: 13366

What sorts of javascript/jquery methods do you routinely code into your sites?

I'm coding a core javascript object for my site, building in the common methods I use (and wrapping a few jQuery methods as well).

It's built like this:

var Core = {
  baseUrl: '/',
  lang: 'en-us',
  loggedIn: false,

  msg: function(str) {
    for (var i = 1, len = arguments.length; i < len; ++i) {
      str = str.replace("{" + (i - 1) + "}");
    }
    return str;
  },
  include: function(url, success, cache) {
    $.ajax({
      url: url,
      dataType: 'script',
      success: success,
      cache: cache !== false
    });
  },
  etc...
}

msg is a method to mimic C# String.Format, include lets me asynchronously pull in scripts. There are others (formatDate: converts datetime string to user's local time, getBrowser: gets browser types based on feature detection, open: opens a link in a new window, etc...)

This core object lets me perform a wide array of tasks... by just calling Core.method... moving nearly all of my javascript code into a .js file which can be cached.

Just out of curiousity, what sorts of common functions do you build into your sites?

Upvotes: 10

Views: 213

Answers (5)

Alexander Pendleton
Alexander Pendleton

Reputation: 314

A logging function is one of the first things I add, if I can't start from Paul Irish's boilerplate.

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

Upvotes: 4

andes
andes

Reputation: 514

I use some convenience methods, handle dynamic theming, grab client info for error reporting and handle theming issues with .NET Postbacks in my core. Here are a couple snippets...

    /**
    *   A convenience method for notifications that can be 
    *   called anywhere in the app, in place of standard 
    *   javascript alerts.  Assuming you define CSS for 
    *   the ID and/or are using jQuery UI, these alerts 
    *   are skinned.
    *
    *   @param string - the message that you want to display
    *   @example - alert('Hello World');
    */
    alert: function(msg) {
        $('body').append('<div id="alert">' + msg + '</div>');
        $('#alert').dialog({
            bgiframe: true
            , modal: true
            , width: 400
            , buttons: {
                Ok: function() { $(this).dialog('destroy'); }
            }
        });
        return this;
    } // EO alert


    /**
    *   .NET Event Handlers
    *   When new code is added on to the client by way of
    *   .NET PostBacks, CSS is typically ignored.  This method
    *   can be used to add CSS to new elements as they are added
    *   asynchronously.  It calls a script at the end of every 
    *   partial post back request.
    *
    *   @example - Core.NETEventHandlers.AsyncPostBack.Init();
    */
    , NETEventHandlers: {
        /**
        *   Async Post Back Handler
        *   calls a script at the end of every partial post back request
        */          
        AsyncPostBack: {
            EndRequest: {
                Add: function() {
                    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Core.NETEventHandlers.AsyncPostBack.EndRequest.Handler); // where Core.NET... leads to this method
                } // EO Add
                , Handler: function(sender, args) {
                    // Handlers here.  Consider adding them into a separate method
                    alert('Hello World');
                } // EO Handler
            } // EO endRequest
            , Init: function() {
                Sys.Application.add_init(Core.NETEventHandlers.AsyncPostBack.EndRequest.Add);   // where Core.NET... leads to this method
            }
        } // EO AsyncPostBack
    } // EO dotNETEventHandlers

Upvotes: 1

wsanville
wsanville

Reputation: 37516

I use some string formatting functions, that are similar to other languages. Usage:

var s = 'Hello {0}!'.format('World'); // result is "Hello World!"
var person = { Name: 'Will' };
var greeting = 'Hello {Name}!'.formatWith(person); // result is "Hello Will!";

And here's the function definitions. I also use simple versions of map and reduce all over the place, not so much on external sites, but on an intranet I go all out with Javascript.

String.prototype.format = function ()
{
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function (capture) { return args[capture.match(/\d+/)]; });
}

String.prototype.formatWith = function (obj, clean)
{
    return this.replace(/\{(.*?)\}/gim, function (all, match) { return obj[match]; });
}

function reduce(fn, a, init, limit)
{
    var s = init;
    var l = (limit == undefined) ? a.length : Math.min(a.length, limit);
    for (i = 0; i < l; i++)
        s = fn(s, a[i], i);
    return s;
}

function map(fn, a)
{
    var l = a.length;
    for (i = 0; i < l; i++)
        a[i] = fn(a[i]);
}

Upvotes: 2

Victor
Victor

Reputation: 5107

I usually add a wrapper for catching any error pages.

ajaxErrorHandle: function (data, container) {
        if (data.indexOf("Server Error in '/' Application") != -1) {
            container.html(data);
            $('.ajax-loader').hide();
            return false;
        }
        return true;
    }

Upvotes: 3

qwertymk
qwertymk

Reputation: 35274

I had a great one for cross-domain ajax with an awesome wrapper, unfortunately I lost it for the moment until I can restore my HD. It was something like this though:

ajax = function(site, callback) {
    $.getScript('get.php?url=' + escape(site) + '&callback=' + callback);
}

ajax.find = function(url) {
    ret = [];
    if (url.match) {
        for (var i = 0; i < this.length; i++)
            if (url.match(this[i].url))
                ret.push(this[i]);
    }
    else
        for (var i = 0; i < this.length; i++)
            if (url === this[i].url)
                ret = this[i];
    return ret;
};

I'm doing this by memory of stuff I wrote once long ago, but you get the point

Upvotes: 0

Related Questions