javascript - Backbone Custom Events -


let's have 2 views (paginationview , postsview) , collection (postscollection). whenever .next button clicked in paginationview calling next function in postscollection , post collection fetching new page's posts server (code simplified). in post view, want display posts in last page. don't want bind view 'add' event in collection because there more cases 'added' collection. want 'renderlist' function in postsview called when 'nextpage' function called in postscollection. how connect these 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 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);     }, }); 

you can use own event purpose.

in collection.nextpage fire event:

this.trigger('nextpage'); 

and in view in initiazlie method bind function event:

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

and don't forget bind context of renderlist (again in initialize method of view):

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

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -