2016-01-27 38 views
0

新手如果這是一個簡單的問題,那麼總的來說就是Backbone的道歉。如何篩選主幹集合並呈現結果

我已成功加載集合並呈現視圖。不過,我有一個A標籤的下拉菜單,我想用過濾器顯示數據。我試圖在我的VIEW中設置一個事件監聽器,然後在視圖中觸發一個函數來過濾結果並重新渲染視圖。

這裏是我的代碼:

IBA.NewsModel = Backbone.Model.extend({}); 
IBA.NewsCollection = Backbone.Collection.extend({ 
    model: IBA.NewsModel, 
    url: "/news/api" 
}); 
IBA.NewsView = Backbone.View.extend({ 
    el: '#main', 
    template: _.template($("#news-article").html()), 

    events: { 
    "change .dropdown-item": "filterNews" 
    }, 

    initialize: function() { 
    this.collection = new IBA.NewsCollection(); 
    this.listenTo(this.collection, 'reset', this.render); 
    this.collection.fetch({ 
     success: function() { 
     console.log("JSON file load was successful"); 
     view.render(); 
     }, 
     error: function(){ 
     console.log('There was some error in loading and processing the JSON file'); 
     } 
    }); 
    }, 

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

    filterNews: function (e){ 
    e.preventDefault(); 
    var items = this.collection.where({cat_name: "interviews"}); 
    console.log(items); 
    this.$el.html(this.template({articles: this.items.toJSON()})); 
    } 
}); 

var view = new IBA.NewsView(); 

回答

0

做這將是實際的收集與篩選的結果重置最簡單的方法:

IBA.NewsModel = Backbone.Model.extend({}); 
IBA.NewsCollection = Backbone.Collection.extend({ 
    model: IBA.NewsModel, 
    url: "/news/api" 
}); 
IBA.NewsView = Backbone.View.extend({ 
    el: '#main', 
    template: _.template($("#news-article").html()), 

    events: { 
    "change .dropdown-item": "filterNews" 
    }, 

    initialize: function() { 
    this.collection = new IBA.NewsCollection(); 
    this.listenTo(this.collection, 'reset', this.render); 
    this.fetchNews(); 
    }, 
    fetchNews: function() { 
    var view = this; 
    this.collection.fetch({ 
     success: function() { 
     console.log("JSON file load was successful"); 
     view.render(); 
     }, 
     error: function() { 
     console.log('There was some error in loading and processing the JSON file'); 
     } 
    }); 
    }, 
    render: function() { 
    this.$el.html(this.template({ 
     articles: this.collection.toJSON() 
    })); 
    return this; 
    }, 

    filterNews: function(e) { 
    e.preventDefault(); 
    this.collection.reset(this.collection.where({ 
     cat_name: "interviews" 
    })); 
    } 
}); 

var view = new IBA.NewsView(); 

當你想回到原來的數據,使用fetchNews()方法再次獲取它。

你也有一個語法錯誤view是不是在你的initialize

+0

感謝TJ定義。該解決方案效果很好。但是,如果我不想每次都重新加載新聞,你會建議採取什麼方法?我有幾個過濾器類別,我認爲這種方法我不得不每次重新加載數據。我可以預設集合並將其分配給每個類別的對象,然後渲染它? – KoalaKid

+0

也出於某種原因,.dropdown項目上的「點擊」事件似乎沒有被附加。這是一個Twitter Bootstrap組件,我猜TB JS已經結束了點擊事件。你知道我怎麼能解決這個問題嗎? – KoalaKid

+0

我剛剛通過「點擊」事件沒有被解僱,似乎除非通過Backbone _template函數呈現DOM,否則它不知道該元素,因此沒有註冊事件。這是標準還是某種問題?有沒有解決這個問題的方法? – KoalaKid