使用Backbone.js的多个页面

HP.*_*HP. 4 javascript node.js backbone.js single-page-application backbone-boilerplate

我使用的是Backbone Boilerplate https://github.com/tbranyen/backbone-boilerplate,不知道处理多个页面的最佳方法是什么.我找不到能帮助我轻松理解的答案.基本上,我在考虑这些选择:

  1. 每个页面应该有不同config.js吗?喜欢config-userpage.js,config-homepage.js......?
  2. 我应该router.js为不同的页面改变不同吗?喜欢router-userpage.js或者router-homepage.js......?
  3. 我应该尝试不同的样板,如https://github.com/hbarroso/backbone-boilerplate吗?

tbr*_*yen 5

你绝对可以尝试不同的样板,但我不确定这会有所帮助.可以通过许多不同方式实现多个页面.

Backbone Boilerplate的一个很好的参考示例是:http://githubviewer.org/ .我已将整个内容作为开源发布,您可以查看基本页面的添加方式.

您可能需要发挥创意并作出处理你在做什么网页上和内部的每个路由设置新的页面标题和布局使用页面模型.

一个非常基本的,概念验证的实现app/router.js可能看起来像这样:

define([
  // Application.
  "app",

  // Create modules to break out Views used in your pages.  An example here
  // might be auth.
  "modules/auth"
],

function(app, Auth) {

  // Make something more applicable to your needs.
  var DefaultPageView = Backbone.View.extend({
    template: _.template("No page content")
  });

  // Create a Model to represent and facilitate Page transitions.
  var Page = Backbone.Model.extend({
    defaults: function() {
      return {
        // Default title to use.
        title: "Unset Page",

        // The default View could be a no content found page or something?
        view: new DefaultPageView();
      };
    },

    setTitle: function() {
      document.title = this.escape("title");
    },

    setView: function() {
      this.layout.setView(".content", this.get("view")).render();
    },

    initialize: function() {
      // Create a layout.  For this example there is an element with a
      // `content` class that all page Views are inserted into.
      this.layout = app.useLayout("my-layout").render();

      // Wait for title and view changes and update automatically.
      this.on({
        "change:title": this.setTitle,
        "change:view": this.setView
      }, this);

      // Set the initial title.
      this.setTitle();

      // Set the initial default View.
      this.setView();
    }
  });

  // Defining the application router, you can attach sub routers here.
  var Router = Backbone.Router.extend({
    routes: {
      "": "index"
    },

    index: function() {
      // Set the login page as the default for example...
      this.page.set({
        title: "My Login Screen!",

        // Put the login page into the layout.
        view: new Auth.Views.Login()
      });
    },

    initialize: function() {
      // Create a blank new Page.
      this.page = new Page();
    }
  });

  return Router;

});
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这是创建"页面"的一种看法,我相信其他人有更好的实现.在Matchbox,我有一个非常强大的页面模型,可以执行面包屑并根据状态确定要突出显示的导航按钮.您还可以在模块中创建路由器以封装功能,并在应用程序对象上公开Page模型,以便在整个应用程序中可用.

希望这可以帮助!