Backbone.js的变更网址无需重新加载页面 [英] Backbone.js change url without reloading the page

查看:232
本文介绍了Backbone.js的变更网址无需重新加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,有一个用户页面的网站。在该页面中,有几个环节,让你探索用户的配置文件。我想使它所以,当这些链接被点击,网址改变,但包含用户的旗帜不重新加载页面的顶部三分之一。

I have a site that has a user page. On that page, there are several links that let you explore the user's profile. I'd like to make it so that, when one of those links is clicked on, the url changes, but the top third of the page containing the user's banner doesn't reload.

我使用Backbone.js的

I'm using Backbone.js

我有一种感觉,我在这些情况下,我有我处理了,我问错了问题的问题,例如缺乏了解1敢,所以请让我知道,如果这似乎是如此

I have a feeling that I'm in one of those situation where I have such a poor understanding of the problem I'm dealing with that I'm asking the wrong question, so please let me know if that appears to be the case

推荐答案

我的错误是假设有在骨干网这样的一个特殊的,内置的方式。没有。

My mistake was assuming that there was a special, built-in way of doing this in backbone. There isn't.

只需运行code的以下行

Simply running the following line of code

window.history.pushState('object or string', 'Title', '/new-url');

将导致您的浏览器的URL更改,恕不重新加载页面。你现在可以在浏览器中打开JavaScript控制台以及与此页尝试。 本文解释比较详细的工作方式(如指出的<一href=\"http://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-page\">this SO帖子)。

will cause your browser's URL to change without reloading the page. You can open up the javascript console in your browser right now and try it with this page. This article explains how it works in more detail (as noted in this SO post).

现在我刚刚绑定以下事件对文档对象(我运行一个单页网站):

Now I've just bound the following event to the document object (I'm running a single page site):

bindEvents: () ->
    $(document).on('click', 'a', @pushstateClick)


pushstateClick: (e) ->
    href = e.target.href || $(e.target).parents('a')[0].href
    if MyApp.isOutsideLink(href) == false
        if e.metaKey 
                      #don't do anything if the user is holding down ctrl or cmd; 
                      #let the link open up in a new tab
        else
            e.preventDefault()
            window.history.pushState('', '', href);
            Backbone.history.checkUrl()

请参阅this帖子获取更多信息。

See this post for more info.

请注意,您可以通过选项 pushState的:真正的您来电Backbone.history.start(),但是这仅仅是使它如此直接导航到一定页面(如example.com/exampleuser/followers)将触发骨干路由,而不是简单地导致一事无成。

Note that you CAN pass the option pushstate: true to your call to Backbone.history.start(), but this merely makes it so that navigating directly to a certain page (e.g. example.com/exampleuser/followers) will trigger a backbone route rather than simply leading to nowhere.

这篇关于Backbone.js的变更网址无需重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆