开发者

Correct way to handle deep linking with jQuery Address

I'm using jQuery Address to handle deep linking with my AJAX application. My URLs are in the format: example.com/#/section/item/param/param/param... I have it setup with the .change() listener to handle different parts of the URL. So /project/my-project/view-item/2/compose would slide open the compose box under that project and that item. The problem is, whenever the URL gets changed to that, every action up to that 开发者_运维知识库point is called. (Actions that happen when the URL is just /project/my-project get called and so on.)

What is the best way to handle just the action I want without "going up the chain"?


The event variable is passed to the change function with the properties: value, path, pathNames, parameterNames, parameters, queryString. The property you want to monitor is pathNames.

Here are some snippets I've put together that could help you keep track of how deep you are as well as what exactly has changed:

var $current_path = window.location.hash;
$.address.change( function(event) {

   // get the difference in the two paths
   $changed_path = event.path.replace(new RegExp('^'+$current_path,'i'), '');

   // make sure we update the current path
   $current_path = event.path;

   // how deep is the new path?
   $level = event.pathNames.length;

   // break the changed part into segments, ignoring leading/trailing slashes
   $changed_path_array = $changed_path.replace(/^\/|\/$/g, '').split('/');

   // let's see what level actually changed from the current path
   $changed_level = $level - $changed_path_array.length;

} );

You can then organize the rest of your function by using the new depth in conjunction with the array of segments to pinpoint exactly what needs to update. Based on the $current_path, you may be performing a fresh page-load or just a tiny change somewhere on the page.


You'll need to keep track of the "current" URL / program state and compare it against what you get in change() to figure out what actions need to be performed next.


It looks like it might benefit you to use something more built-out for advanced client-side routing, such as PathJS. It's very simple to use, and would allow you to do something much more simple and elegant, such as:

// Define a route
Path.map("#/project/my-project/view-item/:id/compose").to(function(){
    var id = this.params["id"]; //get your ID
    $("#panel_" + id).show(); // Do something with the id.
});

// Start listening for changes
Path.listen():
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜