开发者

Converting existing web app to use hashtag URIs using Backbone.js

I'm attempting to use Backbone and it's Router to turn an app into an ajax app, however it currently uses several different methods (helpers) of generating links. Unfortunately, this means manually changing each and every link to use a hashtag is out of the question.

What would be the best method of ensuring every link, form post, redirect, etc. gets parsed as a hashtag URL that can be caught by Backbone's Router? Or, even better, is it possible for the Router to accept "true URL's"开发者_如何学C from a request? Example: a request to /app/mail/inbox.php is caught by a rule in the Router, and is turned into #/mail/inbox after firing the appropriate method to handle the request.


What would be the best method of ensuring every link, form post, redirect, etc. gets parsed as a hashtag URL that can be caught by Backbone's Router?

I don't think that Backbone.Router is supposed to handle, say, form posts. It's supposed to give your application view state—bookmark-friendly and refreshable URLs [1].

If you want to ‘ajaxify’ forms, then you probably should add a handler for form's submit event and do something like $.ajax() there, preventing the default action.

Regarding plain old links, History.pushState() support has been added to Backbone recently. It means that you can define your routes as /app/*, and don't need to replace old href attributes. However, you'll still need to catch link click events to prevent default action.

For example:

var handle_link_click = function(e) {
    path = $(e.target).attr('href');
    app.main_router.navigate(path, true); // This.
    e.preventDefault();
};
$('a:internal').click(handle_link_click);

Router's navigate() method will do history.pushState() if it's available, falling back to old hashchange. And true as a second argument means that it will fire corresponding handler action.

[1] See also this presentation about Backbone

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜