2011-04-25 67 views
3

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

什么是最好的方法来处理我想要的行动,而不是“上链”?

+0

你可以发布一些你的代码吗? – 2011-05-03 01:04:02

回答

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,您可能正在执行全新的页面加载,或者只是在页面某处发生微小的更改。

0

您需要跟踪“当前”URL /程序状态,并将其与您在change()中获得的内容进行比较,以确定接下来需要执行的操作。

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(): 
相关问题