Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone - Update URL from view function

Tags:

backbone.js

I'm stumbling through my first backbone project, and am trying to update the URL after a button element is clicked.

I can manually set the URL via window.location.hash, but I assume this is not the correct way. Can anyone tell me what is the preferred way to update the URL?

var AppView = Backbone.View.extend({
   events: {
        "click #loadProject": "filterProject",
    },
    filterProject: function(){
        var projectID = $('#selectProject option:selected').val();
        var orgID = 'test';

        // Is there a better way to do this?
        window.location.hash = '/'+orgID+'/'+projectID;

        this.renderProject(orgID,projectID);
    },
    renderProject:function(orgID,projectID){
     //Some code
    },
});

//Routing
var PropertiesRouter = Backbone.Router.extend({
    routes: {
        "/:who/:project":"getProjects", //#/org/1
        "/:who":"getOrganisation", //#/org
        "*actions": "defaultRoute"          
    },
    getProjects:function(who,project){
        app.renderProject(who,project);
    },
    getOrganisation:function(who){
        app.renderOrganisation(who);
    },
    defaultRoute: function(actions){
        app.renderHomePage();
    },
});

var app = new AppView();
//create router instance
var propertiesRouter = new PropertiesRouter();
//start history service
Backbone.history.start();

Thanks!

like image 482
Matt Avatar asked May 10 '12 16:05

Matt


1 Answers

You definitely can call window.location.hash, but this does break some of the separation backbone is trying to create for you. A better choice is to call router.navigate(..). See http://backbonejs.org/#Router-navigate

like image 76
robrich Avatar answered Nov 15 '22 14:11

robrich