Xrender
Xrender

Reputation: 1445

backbone go to another page

This is likely a super easy question, in a view, I tie a 'click' event to a button, when that event is clicked I wish to redirect to a totally new page (e.g not a route).

e.g.

events : {      
    "click .button" : 'redirect'
},
redirect : {
     window.location('otherlink');
}

I could use window.location, but seems thats the wrong way? any ideas appreciated?

Upvotes: 7

Views: 18126

Answers (2)

Stephen
Stephen

Reputation: 5470

Backbone has a 'router' (which is basically what I've come to know as a controller). You can use it to do navigation. For example:

var MyApp = new Backbone.Router();
MyApp.navigate('newPage', {trigger: true}); 

trigger makes sure an event is thrown in case you are using said events.

You can team the router up with Backbone's 'history' and build a pretty awesome one page application very easily.

Edit: Never mind, I just re-read that you didn't want to use a route. My two cents - make a wrapper to do the navigation for you. I just had to refactor a pretty big javascript application a few weeks ago, taking out a hundred or so window.locations so that it could be unit tested. Not so much fun. I.e:

MyApp = {
    navigate: function (url) { window.location = url; }
}

Now you can actually do unit testing, as you can override MyApp.navigate with something that does nothing when called. You can also add in business logic if need be.. or filters.. or anything else.. without needing to disturb the rest of the application. For example, if the url is outside of the site, open it in a new window instead of just showing in the same page.

Upvotes: 14

LoG
LoG

Reputation: 1141

I would simply use a simple <a href="otherlink">Link Title</a>. If the link is dynamic I would rely on a View to render the link and manage his state and href.

If you need to do something before letting the user go the the secondary page use and event handler without the event.preventDefault() or avoiding to return false.

Upvotes: 2

Related Questions