开发者

Javascript routes/urls to functions

I'm building a Javascript/AJAX heavy web application using jQuery and I'm looking for a way to map URLs/Routes to Javascript functions. I'm using the HTML5 history API and some rewrite rules so all requests will go to one HTML file but idealy what I'd like to do is something along the lines of

Routes.add('/some/path/', 'func_somepath');
Routes.add('/someother/path/', 'func_someotherpath');

function func_somepath(){
    alert("You're at somepath");
}

function func_someotherpath(){
   alert("You're at someotherpath");
}

Then when someone visited example.com/some/path/ the function 'func_somepath' would be called, similar with /someother/path/. It would also be nice to be able to use Rails-style or regexp variables in the URLs

Routes.add('/items/([a-z]+)', 'func_items');

func_items(id){
   开发者_StackOverflow中文版 alert('You requested '+id+'!');
}

Does anything like this already exist or would I have to write it myself? I don't mind writing it myself but if something already exists there's no point. I'd also like to avoid using 'exec' so how would I go about calling the named functions in Routes.add?


Have you checked out Sinatra's JavaScript counter-part, SammyJS? ...*ba-dum-tish*


Don't use eval unless you absolutely, positively have no other choice.

As has been mentioned, using something like this would be the best way to do it:

window["functionName"](arguments);

That, however, will not work with a namespace'd function:

window["My.Namespace.functionName"](arguments); // fail

This is how you would do that:

window["My"]["Namespace"]["functionName"](arguments); // succeeds

In order to make that easier and provide some flexibility, here is a convenience function:

function executeFunctionByName(functionName, context /*, args */) {
  var args = Array.prototype.slice.call(arguments).splice(2);
  var namespaces = functionName.split(".");
  var func = namespaces.pop();
  for(var i = 0; i < namespaces.length; i++) {
    context = context[namespaces[i]];
  }
  return context[func].apply(this, args);
}

You would call it like so:

executeFunctionByName("My.Namespace.functionName", window, arguments);

Note, you can pass in whatever context you want, so this would do the same as above:

executeFunctionByName("Namespace.functionName", My, arguments);

Hope that helps...


Ember.js, senchatouch2, extjs4 are examples of a framework, that would let you do that easily

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜