【问题标题】:Backbone View: Cannot append a view to a previously rendered view主干视图:无法将视图附加到先前渲染的视图
【发布时间】:2013-01-15 16:43:42
【问题描述】:

这是我的主干代码

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");

app/views/layout.js

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

  template: Template.layout,

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

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

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

我认为这是一个 JQuery 问题,但我无法弄清楚如何以及为什么......

【问题讨论】:

    标签: javascript jquery backbone.js underscore.js


    【解决方案1】:

    问题是你打电话给Backbone.history.start() 太快了。当您启动历史记录时,会立即触发路由,此时您的LayoutView 尚未呈现,并且页面上没有#content 元素。

    骨干docs说:

    在页面加载期间,在您的应用程序完成所有路由器的创建之后,请务必调用 Backbone.history.start() ... [强调我的]

    我喜欢让我的主(“app”)路由器负责启动历史记录,所以我通常在路由器上创建一个start 方法:

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

    然后这样称呼它:

    var appRouter = new AppRouter();
    var otherRouter = new OtherRouter(); // if you have any
    appRouter.start();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      相关资源
      最近更新 更多