2013-07-10 3 views
10

두 개의보기 (paginationview 및 postsview)와 컬렉션 (postscollection)이 있다고 가정 해 보겠습니다. paginationview에서 .next 버튼을 클릭 할 때마다 나는 postscollection에서 다음 함수를 호출하고 있는데, 포스트 콜렉션은 서버에서 새로운 페이지의 포스트를 가져 오는 것입니다 (코드는 단순화됩니다). 이제 내 글보기에서 마지막 페이지에있는 게시물 만 표시하고 싶습니다. 컬렉션에 '추가'이벤트가 발생하는 경우가 더 많아지기 때문에 내 뷰를 바인딩 할 필요가 없습니다. 내 postscollection에서 'nextPage'함수가 호출 될 때만 내 postsview의 'renderlist'함수를 호출해야합니다. 이들을 함수에 함께 연결하려면 어떻게해야합니까?백본 사용자 정의 이벤트

// 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); 

그리고 문맥을 결합하는 것을 잊지 마세요 renderlist를 이것 (다시보기 초기화 메서드에서) :

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

아마 this.tr igger ('nextpage');는 대개 가져 오기의 성공 처리기에서 발생해야합니다. –

+0

그 앤드류가 무엇을 의미합니까? 반입이 성공적 일 때만 발생해야합니까? 그렇지 않으면 가져 오기 전에 renderlist가 호출 될 수 있습니까? –

+0

네, 앤드류 말이 맞아요. 페칭이 끝날 때까지 기다려야합니다. 따라서 우리는 성공에 대한 사건을 유발할 수 있습니다. –