Search code examples
javascriptjquerybackbone.js

Backbone.js execute function when subview is clicked


I have a view named DatesView and a subview named DateView. I would like to execute a function in DatesView when an instance of DateView is clicked.

var Date = Backbone.Model.extend({});

var Dates = Backbone.Collection.extend({
    model: Date
});

var DateView = Backbone.View.extend({
    events: {
        'click': 'clicked'
    },

    render: function () {
        this.$el.text(this.model.get('date'));

        return this;
    }
})

var DatesView = Backbone.View.extend({
    render: function () {
        this.collection.each(function (date) {
            var dateView = new DateView({model: date});

            this.$el.append(dateView.render().el)
        }, this);

        return this;
    },

    clicked: function() {
        console.log('clicked');
    }
})

var dates = new Dates([
    {date: '01'},
    {date: '02'},
    {date: '03'}
])

var datesView = new DatesView({collection: dates});

$('#container').html(datesView.render().el);

JSFiddle

As you can see in the example the DateView has an event setup for click, which I would like to register in the DatesView. The way it is written now does not work.


Solution

  • I quite like using Backbone events. You can use it as follows:

    Trigger the event in your DateView

    clicked: function () {
        Backbone.trigger('date:clicked');
    }
    

    Listen for the event in the DatesView

    initialize: function () {
        this.listenTo(Backbone, 'date:clicked', this.clicked);    
    }