0

これが私のバックボーンコードです

app.js

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

window.Template = {};

app/router.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);
  }
});

app/templates.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

問題は、電話をかけるのBackbone.history.start()が早すぎることです。履歴を開始すると、ルートがすぐにトリガーされます。その時点でLayoutViewは、まだレンダリングされておらず#content、ページに要素はありません。

バックボーンドキュメントは言う:

ページの読み込み中に、アプリケーションがすべてのルーターの作成を完了した後、必ずBackbone.history.start()...[emphasismine]を呼び出してください。

メイン(「アプリ」)ルーターに履歴の開始を任せたいので、通常startはルーター上にメソッドを作成します。

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

そしてそれをそのように呼びます:

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