【问题标题】:Routing Backbone路由骨干网
【发布时间】:2016-03-02 02:07:30
【问题描述】:

我正在尝试在 Backbone 上进行路由,但此时它对我来说非常神秘。这就是我所拥有的

    routes: {
        ''            : 'home',
        'home'        : 'home',
        'departments' : 'departments',
        'employees'   : 'employees',
        'requests'    : 'requests'
    },

    home: function(){
        new app.HomeView();
    },

这是在我的路由器内部,显然我调用了 Backbone.history.start()。在我看来,我有定义渲染函数并从初始化方法调用它的模式。

    el: '#containerList',

    template: Handlebars.compile( $('#home-template').html() ),

    initialize: function(){         
        this.render();
    },

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

HTML:

<section id='main' class='container'>
  <section id='containerList'></section>
</section>

我有以下问题:

  1. 在返回按钮上,视图被附加。我需要重新加载页面来解决这个问题。
  2. 每当在浏览器搜索栏上写入路线时,我都需要重新加载两次以显示视图。它的行为非常不稳定,有时它会在没有集合的情况下呈现视图。

我已经阅读了很多策略,要在 CloseView 上使用事件,在离开视图时使用 this.remove。显然这对我没有任何作用。我几乎看不到主干上的路由器文档。

【问题讨论】:

  • 由于您要替换整个 html,例如 this.$el.html( this.template());,因此不太可能添加某些内容...您可以创建一个 minimal reproducible example..?

标签: javascript backbone.js


【解决方案1】:

我建议实现一个函数来添加和删除当前路线的主视图。所以你的路由器看起来像:

routes: {
        ''            : 'home',
        'home'        : 'home',
        'departments' : 'departments',
        'employees'   : 'employees',
        'requests'    : 'requests'
    },

    home: function(){
        var view = new app.HomeView();
        this.setMainView(view);      
    },

    setMainView: function(view) {
            this.mainView && this.mainView.remove();
            this.mainView = view;
            this.mainView.setElement($('#main'));
   }

然后您不需要预定义视图的 el,因此您的视图将如下所示:

var HomeView = Backbone.View.extend({
    template: Handlebars.compile( $('#home-template').html() ),

    initialize: function(){         
        this.render();
    },

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

})

基本上,您有一个包含当前主视图 (#main) 的 div 元素,并且在每个路由函数上,您需要调用 setMainView 函数来设置当前视图。

【讨论】:

    猜你喜欢
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 2016-03-31
    相关资源
    最近更新 更多