Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh a page in a backbone application

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?

like image 847
Zhen Avatar asked Jan 17 '12 20:01

Zhen


People also ask

How does Backbone JS work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Why use Backbone JS?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

What is Backbone in Programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


2 Answers

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, returns false.

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;   } } 
like image 86
amiuhle Avatar answered Sep 28 '22 07:09

amiuhle


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);     } }); 
like image 42
3 revs Avatar answered Sep 28 '22 06:09

3 revs