2014-06-24 26 views
0

我有一個Backbone應用程序,其中顯示基於JSON數據的模型集合。在JSON數據內部,我有endDate - 它給了我實時的日期。它基於競爭模塊。我想要實現的是,如果給定的日期已經過期,我想隱藏(甚至可能刪除)集合中的模型,這樣競爭就不再可用。BackboneJS當日期已過期時隱藏模型

到目前爲止,我competition.js,在底部的模式是這樣的:

Competition.View = Backbone.View.extend({ 
    tagName: 'ul', 
    template: 'competition', 
    initialize: function() { 
     this.listenTo(this.model, 'sync', this.render);    
    }, 
    serialize: function() { 
     return this.model.toJSON(); 
    } 
}); 

Competition.CompetitionModel = Backbone.Model.extend({ 
    url: function() { 
     return App.APIO + '/i/contests'; 
    }, 
    comparator: function(item) { 
     return item.get('endDate'); 
    }, 

    defaults: { 
     "data": [] 
    } 
}); 

然後我的主模塊中,我導入competition.js,這裏我取模型,並使其在特定HTML元素(不知道它需要複製/粘貼在這裏爲我原來的問題):

function (App, Backbone, Competition) { 

    var CompetitionOverview = App.module(); 

    CompetitionOverview.View = Backbone.View.extend({ 
     template: 'competitionOverview', 
     initialize: function(){ 
      this.render(); 
     }, 
     beforeRender: function() { 
      var competitionModel = new Competition.CompetitionModel(); 
      this.insertView('.singleComp', new Competition.View({model: competitionModel})); 
      competitionModel.fetch(); 
     }, 

    }); 

    return CompetitionOverview; 
} 

所以,我怎樣才能實現隱藏/刪除該日期已經過期的模型?

在此先感謝...

+0

如果下面的答案幫你解決這個問題,請接受的答案。謝謝。 – jorrebor

回答

0

幽州,你有模型的集合,但你Competition.CompetitionModel擴展Backbone.Model而不是Backbone.Collection。在我的回答中,我假設CompetitionModel是Backbone.Collection而不是Backbone.Model

這麼說,我覺得你有兩個選擇:

  1. 入住的Competition.View渲染功能,你是否真的應該給出一個對結束日期的東西:

    Competition.View = Backbone.View.extend({ 
        tagName: 'ul', 
        template: 'competition', 
        initialize: function() { 
         this.listenTo(this.model, 'sync', this.render);    
        }, 
        serialize: function() { 
         return this.model.toJSON(); 
        }, 
        render: function(){ 
          //dependending on in which format your date is you might have to convert first. 
          if(this.model.get('endDate') < new Date().getTime()){ 
           //render the view 
          } 
    }); 
    
  2. 或者,並且我認爲這樣更乾淨一些,只要數據從服務器進入就檢查日期。當從服務器獲取集合時,我認爲骨幹會在集合上觸發「添加」事件。所以,再次,讓你的競爭模型成爲一個競賽收集,並收聽添加事件。更改

    Competition.CompetitionModel = Backbone.Collection.extend({ 
        initialize: function() { 
         this.on("add", checkDate) 
        }, 
        checkDate: function(model, collection, options){ 
         //again, get the right conversion 
         //but here you should compare your end date with the expire date 
         if(model.get('endDate') < new Date().getTime()){ 
          this.remove(model.id); 
         } 
        }, 
        url: function() { 
         return App.APIO + '/i/contests'; 
        }, 
        comparator: function (item) { 
         return item.get('endDate'); 
        }, 
    
        defaults: { 
         "data": [] 
        } 
    });