使用jQuery Address处理深层链接的正确方法

时间:2011-04-25 18:37:08

标签: jquery deep-linking jquery-address

我正在使用jQuery Address来处理与我的AJAX应用程序的深层链接。我的网址格式为:example.com/#/section/item/param/param/param...我设置了.change()侦听器来处理网址的不同部分。因此/project/my-project/view-item/2/compose会滑动打开该项目下的撰写框和该项目。问题是,无论何时将URL更改为该值,都会调用到该点为止的每个操作。 (当URL刚刚/project/my-project被调用时发生的操作等等。)

在没有“上链”的情况下,处理我想要的动作的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

事件变量传递给change函数,其属性为:value, path, pathNames, parameterNames, parameters, queryString。您要监控的属性是pathNames

以下是我汇总的一些片段,可以帮助您跟踪您的深度以及确切变化的内容:

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;

} );

然后,您可以通过将新深度与段数组结合使用来精确确定需要更新的内容,从而组织其余功能。根据$ current_path,您可能正在执行新的页面加载或页面上的某个小变化。

答案 1 :(得分:0)

您需要跟踪“当前”网址/计划状态,并将其与change()中的内容进行比较,以确定接下来需要执行的操作。

答案 2 :(得分:0)

对于使用更加内置的高级客户端路由(例如PathJS),您可能会受益。它使用起来非常简单,并且可以让您做一些更简单和优雅的事情,例如:

// 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():