views:

979

answers:

4

Are there any commonly used patterns in Javascript for storing the URL's of endpoints that will be requested in an AJAX application?

For example would you create a "Service" class to abstract the URL's away?

A: 

Is your question similar to this already-answered question? If so, does the answer apply to your code also?

John Millikin
A: 

Where you store your globals is a matter of personal choice. It's best to put them inside an object to avoid conflicts in the global namespace, so yes, a global object named Service would be a good place to store URLs, and other strings that are used in multiple places.

Joel Anair
+1  A: 

You could create a collection of ValuePairs where you'd store each URL value and an identifier:

function ControlValuePair(Id, Value)
{   
    this.Id = Id;
    this.Value = Value;
}

function CreateCollection(ClassName)    
{
    var obj=new Array();
    eval("var t=new "+ClassName+"()");
    for(_item in t)
        {
            eval("obj."+_item+"=t."+_item);
        }
    return obj;
}

function ValuePairsCollection()
{
    this.Container="";
    this.Add=function(obj)
    {
        this.push(obj);
    }
}

Later you can iterate through the collection or look up the id.

David Robbins
A: 

I've used something like this (used in Rails):

NAMESPACE.categories.baseUri = '/categories';
NAMESPACE.categories.getUri = function(options)
{
  options = options || {};
  var uri = [NAMESPACE.categories.baseUri];

  if(options.id)
  {
    uri.push(options.id); 
  }
  if(options.action)
  {
    uri.push(options.action);
  }
  if(options.format)
  {
    uri.push('?format=' + options.format);
  }

  return uri.join('/');
}
Ben