2012-12-14 55 views
1

我创建一个单页滚动网站。这意味着来自json的所有数据立即被加载,并且每次散列更改时都不需要多次获取数据。backbone.js抓取页面一次

var AppRouter = Backbone.Router.extend({ 
routes: { 
    ""   : "index", 
    ":page" : "page" 
}, 

index: function() { 
    console.log('list'); 
    this.init = new WH.ExperienceCollection(); 
    this.book = new WH.ExperienceBook({model: this.init}); 
    this.init.fetch(); 
}, 

page: function(page) { 
    this.init = new WH.ExperienceCollection(); 
    this.book = new WH.ExperienceBook({model: this.init}); 
    this.init.fetch({success: function(data){ 
     WH.utils.resize(); 
     $('html,body').stop(true, true).animate({scrollTop: $('#'+page).offset().top}, 500); 
    }}); 
} 

});

是我的路线。当哈希值变化时,我希望它向下滚动到该部分。现在,该页面不断提取并添加页面上已有的内容。

回答

1

如果集合已被提取,您应该将其存储在变量中。然后,根据这个变量,重新提取或不提取。

例如:

var AppRouter = Backbone.Router.extend({ 

    init: new WH.ExperienceCollection(), 
    book: new WH.ExperienceBook({model: this.init}), 
    fetched: false, 

    routes: { 
     ""   : "index", 
     ":page" : "page" 
    }, 

    index: function() { 
     console.log('list'); 
     this.init = new WH.ExperienceCollection(); 
     this.book = new WH.ExperienceBook({model: this.init}); 
     this.init.fetch(); 
    }, 

    page: function(page) { 
     var self = this; 
     if(this.fetched) { 
      render(); 
     } else { 
     this.init.fetch({success: render}); 
     } 

     function render(){ 
      self.fetched = true; 
      Westin.utils.resize(); 
      $('html,body').stop(true, true).animate({scrollTop: $('#'+page).offset().top}, 500); 
     } 
    } 
}); 

有可能取决于你的收藏里有什么其他的解决办法。但作为全球性的答案,这是最一般的情况。但是,例如,您也可以测试集合的长度以查看它是否被填满,或者检查模型中是否存在值等。想法是告诉您集合/模型是否取或不取。

1

如果它需要为每路线(或其中许多),然后put it in the Router's initialize function

var AppRouter = Backbone.Router.extend({ 
    initialize: function() { 
     if (!this.init) { 
      console.log("fetching init..."); 
      this.init = WH.ExperienceCollection(); 
      this.book = new WH.ExperienceBook({ model: this.init }); 
      this.init.fetch(); 
     } else { 
      console.log("init already fetched!"); 
     } 
    }, 
}); 

第一次加载页面时这将运行一次。