Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js - events only firing once

My events aren't working as I'd hoped, and I think I know why. When the perpage span is clicked, everything renders correctly. But I realized - maybe the events aren't reattached to the new markup? Could that be why it only works once? (If I click the span with the number 10 in it, 10 items appear like it should be. But afterwards, anything I click doesn't change anything)

What's a better way to organize this? Should the template not include the pagination portion? How do I attach backbone events to markup after it has rendered again?

var ListView = Backbone.View.extend({

    initialize: function() {
        var self = this;
        this.collection.bind("refresh", function(){self.render();});
        this.render();
    },

    events: {
        'click ul#perpage span': 'setperpage'
    },

    setperpage: function(event) {
        this.collection.perpageurl = '/perpage/' + $(event.target).text();
        this.collection.fetch();
        this.collection.refresh();
    },

    render: function() {

    template = _.template('\
    <table>\
    <% _(collection).each(function(model){%>\
    <tr><td><%=model.id%></td><td><%=model.name%></td><td><%=model.email%></td></tr>\
    <%}); %>\
    </table>\
    <ul id="perpage">\
    <li><span>5</span></li>\
    <li><span>10</span></li>\
    </ul>\
    ');

        var context = {collection: this.collection.toJSON()};
        $(this.el).html(template(context));
        $('#app').html(this.el);
        return this;
    }
});
like image 443
Matthew Avatar asked Dec 22 '22 15:12

Matthew


1 Answers

try:

render: function()
{
    // …

    this.delegateEvents();
    return this;
}

For debugging events in JavaScript use Visual Event. It will tell you which elements have events attached to them.

like image 193
pawlik Avatar answered Dec 28 '22 05:12

pawlik