Backbone - 从视图功能更新URL

时间:2012-05-10 16:02:30

标签: backbone.js

我在第一个骨干项目中磕磕绊绊,并且在点击按钮元素后尝试更新URL。

我可以通过window.location.hash手动设置URL,但我认为这不是正确的方法。任何人都可以告诉我更新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();

谢谢!

1 个答案:

答案 0 :(得分:8)

你绝对可以打电话给window.location.hash,但这确实打破了一些试图为你创造的分离主干。更好的选择是致电router.navigate(..)。见http://backbonejs.org/#Router-navigate