BackboneJS避免重新渲染

时间:2014-09-01 13:44:15

标签: javascript backbone.js

我有一个带有大型路由器的Backbone App。我使用Backbone布局管理器来加载不同的布局,具体取决于我所在的子页面。我的问题是,每次子页面渲染时,我的顶部导航会再次渲染。那我怎么能避免这个呢?

我的路由器:

routes: {
    '': 'index',
    'home': 'home',     
    ':name' : 'artistchannel',
    ':name/' : 'artistchannel',
    ':name/videoes': 'artist_videos',
    ':name/videoes/': 'artist_videos',
    ':name/videoes?w=:videoid' : 'artist_videos',
    ':name/releases': 'artist_discography',
    ':name/releases/': 'artist_discography',
    ':name/merchandise' : 'artist_merchandise',
    ':name/concerts': 'artist_concerts'
},

artistchannel: function (params) {
    artistController.initArtist(params.name);
},
artist_discography: function(params){
    artistController.initDiscography(params.name);
},
 and so on...

然后我为每条路线设置了一个控制器(这里是艺术家和唱片页面):

ArtistController.prototype.initArtist = function(name) {
    this.artistModel = new ArtistModule.Model({slug: name});
    this.artistModel.fetch();
    this.artistModel.on('sync', function(){
        this.artistView = new ArtistModule.View({model: this.artistModel});
        App.useLayout('artistchannel', 'artistchannel').setViews({
            '.userMenu': this.acuserNav,
            '.artistChannelDiv': this.artistView
        }).render();
    }, this);
    window.scrollTo(0,0);
};

ArtistController.prototype.initDiscography = function(name) {
    this.artistdiscographyModel = new ArtistDiscographyModule.ArtistDiscographyModel({slug: name});
    this.artistdiscographyModel.fetch();
    this.artistdiscographyModel.on('sync', function() {
        this.artistDiscographyView = new ArtistDiscographyModule.View({model: this.artistdiscographyModel});
        App.useLayout('artistDiscography', 'artistDiscography').setViews({
            '.userMenu': this.acuserNav,
            '.releasesDiv' : this.artistDiscographyView
        }).render();
    }, this);
    window.scrollTo(0,0);
};

同样适用于音乐会,商品等。

所有子页面(在本例中为artistchannel.html和artistDiscography.html)在HTML中都有相同的菜单,我想避免使用,所以基本上,它的重复代码如下所示:

<ul>
   <li>
      <a href="{{name}}/releases">Releasepage</a>
   </li>
   <li>
      <a href="{{name}}/concerts">Concertpage</a>
   </li>
   etc. etc.
</ul>

所以我想要的是topmenu不会一直被重新渲染。是否可以在一个控制器中包含所有内容?

1 个答案:

答案 0 :(得分:0)

有布局&amp; ShellView / MenuView。不要将每个视图的$ el附加到正文,而是为每个特定视图使用容器。一种方法可以是:

<body>
    <div id='menu'></div>
    <div id='content'></div>
</body>


new Backbone.Router.extend({
   initialize:function(){
       new MenuView({el:"#menu"}).render();  //this one creates menu
   },
   routes:{...},
   routeHandler:function(){
     new ArtistVideosView({el:'#content'}).render();
   }
});
相关问题