How to refresh a page in a backbone application

2019-03-08 10:31发布

I am using backbone to build my web app.

Currently I am facing an issue whereby if I am on the home page, I am unable to refresh the same page by just clicking on the 'home' button again.

I believe that this is the limitation provided by backbone (does not reload the page if the same URL is called)

enter image description here

Is there any way around this? So that I can trigger a page reload when I click on the home button again i.e. call the same URL again?

13条回答
We Are One
2楼-- · 2019-03-08 11:11

The difference between http://localhost.com/ and http://localhost.com/#!/ is that the second is a link to anchor, it does not load a page, it only looks for the anchor in the current page, and scrolls to it if found. You need to make your link looks like the first one, no "#" close to end.

查看更多
Melony?
3楼-- · 2019-03-08 11:14

The backbone.history.loadUrl is the solution.

The click handling function of your Home button (if the home is the root / of your WebApp) should be:

myAppRouter.navigate('');
Backbone.history.loadUrl();
查看更多
混吃等死
4楼-- · 2019-03-08 11:14

Here's my favorite approach so far:

 if (!Backbone.history.navigate(urlPath, true)) {
      Backbone.history.loadUrl();
 }
查看更多
爷的心禁止访问
5楼-- · 2019-03-08 11:15

This is not upto backbone. The same works fine in chrome(webkit browsers), but not in firefox. Its a browser behavior

查看更多
成全新的幸福
6楼-- · 2019-03-08 11:22

Looking at the backbone.js source, it seems as though this is not possible by default, since it only responds to a url change. And since clicking the same link, you would not trigger a change event.

Code in Backbone.History:

$(window).bind('hashchange', this.checkUrl);

You'll need to handle a non-change yourself. Here's what I did:

$('.nav-links').click(function(e) {
    var newFragment = Backbone.history.getFragment($(this).attr('href'));
    if (Backbone.history.fragment == newFragment) {
        // need to null out Backbone.history.fragement because 
        // navigate method will ignore when it is the same as newFragment
        Backbone.history.fragment = null;
        Backbone.history.navigate(newFragment, true);
    }
});
查看更多
神经病院院长
7楼-- · 2019-03-08 11:23

I needed to 'refresh' my page on orientation change event because not all of my css media queries for portrait mode where executed correctly by default. This is what I ended up doing:

Backbone.history.fragment = null;
Backbone.history.navigate(document.location.hash, true); 

Of course, for the completeness of this answer, this was wrapped in some orientation change handling code:

window.addEventListener('orientationchange', function () {
    Backbone.history.fragment = null;
    Backbone.history.navigate(document.location.hash, true); 
}, false);
查看更多
登录 后发表回答