0

这是我的主干代码

应用程序.js

window.App = {
Models: {},
Views: {}
};

window.Template = {};

应用程序/路由器.js

App.Router = Backbone.Router.extend({

  initialize: function () {
    Backbone.history.start({pushState: true});
    App.layout = new App.Views.Layout();
    App.layout.render();
    $('#app').append(App.layout.el);
  },

  routes: {
    '': 'index'
  },

  index: function () {
     console.log('index routed.');
     App.home = new App.Views.Home();
     App.home.render();
     $('#content').html(App.home.el);
  }
});

应用程序/模板.js

Template.layout = _.template(
  "<header id=top-bar>"+
  "<nav id=user-panel>"+
  "<ul>"+
  "<li><a class=login href=#>Login</a></li>"+
  "<li><a class=register href=#>Registrati gratis</a></li>"+
  "</ul>"+
  "</nav>"+
  "</header>"+
  "<div id=wrapper>"+
  "<section id=mid-bar>"+
  "<a id=logo href=#><img src=public/img/logo.png></a>"+
  "</section>"+
  "<section id=content>"+
  "</section>"+
  "</div>"
);

Template.home = _.template("Benvenuto in Virtualmix");

应用程序/视图/layout.js

App.Views.Layout = Backbone.View.extend({
  id: 'container',

  template: Template.layout,

  render: function () {
    this.$el.html(this.template);
  }
});

应用程序/视图/home.js

App.Views.Home = Backbone.View.extend({

  tagName: 'p',

  template: Template.home,

  render: function () {
    this.$el.html(this.template);
  }
});

最后是我的 main.js

$(document).ready(function () {
  App.router = new App.Router;
});

好吧,布局视图(从路由器初始化函数初始化......)被正确渲染,但是从索引函数初始化和渲染的主视图似乎在我之前生成的布局上没有输出任何内容(我想在#content 由布局生成的元素...)。

我认为这是一个 JQuery 问题,但我不知道如何以及为什么......

4

1 回答 1

1

The problem is that you're calling Backbone.history.start() too soon. When you start the history, the route is triggered immediately, at which point your LayoutView is not yet rendered, and there is no #content element on the page.

The Backbone docs say:

During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start() ... [emphasis mine]

I like to still have my main ("app") router be in charge of starting the history, so I usually create a start method on the router:

AppRouter = Backbone.Router.extend({
  start: function() {
    Backbone.history.start();
  },
  //...
});

And call it like so:

var appRouter = new AppRouter();
var otherRouter = new OtherRouter(); // if you have any
appRouter.start();
于 2013-01-15T16:58:18.397 回答