Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  198] [ 6]  / answers: 1 / hits: 15451  / 11 Years ago, wed, july 10, 2013, 12:00:00

Let's say I have two views (paginationview and postsview) and a collection (postscollection). Whenever the .next button is clicked in the paginationview I am calling the next function in the postscollection and the post collection is fetching the new page's posts from the server (code is simplified). Now in my post view, I only want to display the posts that are in the last page. I don't want to bind my view to the 'add' event in the collection because there are more cases that something is 'added' to the collection. I want my 'renderlist' function in my postsview only to be called when the 'nextPage' function is called in my postscollection. How do I connect these to functions together?



// paginationview



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

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


// collection



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);
},
});

More From » backbone.js

 Answers
46

You can use your own event for this purpose.



In Collection.nextPage you fire the event:



this.trigger('nextpage');


and in view in initiazlie method you bind your function to this event:



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


And also don't forget to bind context of renderlist to this (again in initialize method of view):



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

[#77080] Tuesday, July 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaden

Total Points: 709
Total Questions: 91
Total Answers: 91

Location: Maldives
Member since Sat, Jan 29, 2022
2 Years ago
;