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 \'
It works with
myBackboneRouter.navigate("users", {trigger: true})
In order to provide a reusable snippet of code I augmented the Backbone.View with a helper method to reuse it wherever we need to reload the same page despite the Backbone router limitations.
In our app.js file or any other proper place
Backbone.View = Backbone.View.extend({
refreshPage: function(e){
if(e.target.pathname){
Backbone.history.navigate(e.target.pathname);
}
window.location.reload();
}
});
This way if we have a link such as
<a href="/whatever" id="whateverId">Some text </a>
In our View we would just need to bind the click event to that callback to leverage the refresh page feature, as far as the refreshPage helper will be available through the prototype chain
events: {
'click #whateverId': 'refreshPage',
}
As far as we don't need to change the "a tag" it's a cleaner solution that will save some boilerplate coding
Hope it helps
You could also just make a meaningless change to the url by adding a random number to the end:
var url = $(this).attr('href') + '?rand=' + Math.floor(Math.random() * 1000);
Backbone.history.navigate(url, true);
This is especially useful for IE since it will not request new data via an AJAX call if the url has not changed.
In case you want to reload the whole page with a desired view. This might make senes for the home button. The advantage will be that it'll refresh the memory.
Go to any route without loading it (without the 'true') and then reload
Backbone.history.navigate('route/goes/here');
window.location.reload();
You're looking for Backbone.history.loadUrl
.
From the Annotated Source:
Attempt to load the current URL fragment. If a route succeeds with a match, returns
true
. If no defined routes matches the fragment, returnsfalse
.
So, for a simple refresh link, you can add the following event to your Backbone.View
:
events: {
'click a#refresh': function() {
Backbone.history.loadUrl();
return false;
}
}
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);
}
});