Backbone Custom Events

Gorkem Yurtseven picture Gorkem Yurtseven · Jul 10, 2013 · Viewed 14.9k times · Source

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

Answer

Artem Volkhin picture Artem Volkhin · Jul 10, 2013

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