I'm writing a front-end to my RESTful API using Backbone... and I'm really enjoying it so far. Learning this framework continues to be super interesting. However, I am now stumped on something that seems like, to me at least, that it should be straight forward.

I now have a single (and only) html page where the main application resides that lists one or more products. And, lets say it resides here: http://localhost/index.html

I would like to be able to switch from the product list view to the new product view (via click event on a button at the top). And that, from what I understand, I need to begin using a router for switching using the pattern described in How to switch views using Backbone.js.

  1. Is view-switching what I need to be doing to achieve this behavior?
  2. This looks hokey:

    http://localhost/index.html#product/new

    And, since I'm using [tornado](http://tornadoweb.org) as my web server for both my API and static content, I can't just implement a rewrite rule easily. I may switch to using nginx for static content in the near future, but I haven't yet. If I'm to use a router to switch views like when going from Review to Create (of CRUD operations), how do I change the URL/URI to look something more along the lines of this

    http://localhost/product/new
有帮助吗?

解决方案

In order to receive hashless url changes, your browser has to support pushstate. If I am not mistaken, Backbone will fallback to using hashes if your browser does not support pushstate. You would initialize your router with the following in order to use pushstate in your application:

Backbone.history.start({pushState: true})

I like @alexanderb's use of view switching. Just MAKE sure when you are changing views, you dispose of them properly. Otherwise you will run into some complex problems that are difficult to debug. Read more here.

其他提示

Yes, you need 2 things - Router and ApplicationViewManager (some class, that is responsible for changing the view).

define(function () {

var ViewManager = function () {
    return {
        show: _showView
    };
};

function _showView(view) {
    if (this.currentView) {
        this.currentView.close();
    }

    this.currentView = view;
    this.currentView.render();

    $("#app").html(this.currentView.el);
}

return ViewManager;

});

In router, you do something like:

// router
var ApplicationRouter = Backbone.Router.extend({

    initialize: function () {
        this.viewManager = new ViewManager();
    },

    routes: {
        '': 'dashboard',
        'configure/sites/:id': 'configure'
    },

    dashboard: function () {
        var app = require('./apps/DashboardApp');
        app.run(this.viewManager);
    },

    configure: function (id) {
        var app = require('./apps/ConfigureApp');
        app.run(id, this.viewManager);
    }

});

Some code examples, you can take from this repository.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top