2013-07-10 156 views
10

比方說,我有兩個視圖(paginationview和postsview)和一個集合(postscollection)。無論何時在paginationview中單擊.next按鈕,我都會調用postscollection中的下一個函數,並且post集合正在從服務器獲取新頁面的帖子(代碼已被簡化)。現在在我的帖子視圖中,我只想顯示最後一頁中的帖子。我不想將我的視圖綁定到集合中的「添加」事件,因爲有更多情況是「添加」到集合中的。我希望我的postsview中的'renderlist'函數僅在我的postscollection中調用'nextPage'函數時被調用。我如何將這些功能連接在一起?骨幹自定義事件

// paginationview

var PaginationView = Backbone.View.extend({ 
    events:{ 
     'click a.next' : 'next', 
    }, 

    next: function() { 
     this.collection.nextPage(); 
     return false; 
    } 
}); 

//收集

var PostsCollection = Backbone.Collection.extend({ 
    model: model, 

    initialize: function() { 
     _.bindAll(this, 'parse', 'url', 'pageInfo', 'nextPage', 'previousPage'); 
     this.page = 1; 
     this.fetch(); 
    }, 

    parse: function(response) { 
     console.log(response); 
     this.page = response.page; 
     this.perPage = response.perPage; 
     this.total = response.total; 
     this.noofpages =response.noofpages; 
     return response.posts; 
    }, 

    url: function() { 
     return '/tweet/' + '?' + $.param({page: this.page}); 
    }, 

    nextPage: function() { 
     console.log("next page is called"); 
     this.page = this.page + 1; 
     this.fetch(); 
    }, 

// postsview

var PostsView = Backbone.View.extend({ 
    events:{ 
     'click #testbutton' : 'test', 
     'click #allbutton' : 'render', 
    }, 

    initialize: function() { 
     this.listenTo(this.collection, 'add', this.addOne); 
    }, 

    render: function() { 
     $(".maincontainer").html(""); 
     this.collection.forEach(this.addOne, this); 
     return this; 
    }, 

    renderlist: function(){ 
     $(".maincontainer").html(""); 
     this.collection.forEach(this.addOne, this); 
    }, 

    addOne: function(post) { 
     var post = new postView({model : post}); 
     post.render(); 
     this.$el.prepend(post.el); 
    }, 
}); 

回答

13

您可以使用自己的事件作此用途。

在Collection.nextPage你觸發事件:

this.trigger('nextpage'); 

,並鑑於initiazlie方法,你的功能綁定到該事件:

this.listenTo(this.collection, 'nextpage', this.renderlist); 

而且也不要忘了結合上下文(再次初始化視圖的方法):

_.bindAll(this, 'render', 'rederlist'); 
+1

這可能是一個好主意,注意'this.tr igger('nextpage');'應該可能發生在獲取的成功處理程序中。 –

+0

那是什麼意思,安德魯?應該只在抓取成功時纔會發生?否則renderlist可能在獲取之前被調用? –

+0

是的,安德魯是對的。我們應該等到提取完成。所以我們可以觸發成功事件。 –