Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone click event fires events for all collection rather than model

Can't figure out what's wrong. When I click on a model title, it fetches all models in collection at once rather than fetch one model. If I move this event from logView to logsView it works properly but doesn't have access to model, well I can find this model using index or ant other model's ID but don't think this is a nice way.

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


window.LogsList = Backbone.Collection.extend({
    model:Log,

    url:function (tag) {
        this.url = '/logs/' + tag;
        return this;
    }
});

window.colList = new LogsList();

window.logView = Backbone.View.extend({
    el:$('.accordion'),

    template:_.template($('#log').html()),

    initialize:function () {
        this.model.bind('add', this.render, this);
    },

    events:{
        "click .accordion-toggle" :"getLogBody"
    },

    render:function () {
        return this.template(this.model.toJSON());
    },

    getLogBody:function () {
        this.model.fetch();
    }
});

window.LogsView = Backbone.View.extend({
    el:$("#content"),

    initialize:function (options) {
        colList.bind('reset', this.addAll, this);
        colList.url(options.data).fetch();
    },

    addOne:function (model) {
        var view = new logView({model:model});
        $("#accordion").append(view.render());
    },

    addAll:function () {
        colList.each(this.addOne);
    }
});

window.listView = new LogsView({data:"Visa_Cl"});
like image 573
nateless Avatar asked Feb 12 '12 19:02

nateless


1 Answers

The problem is caused by your el in the LogView: el:$('.accordion')

Backbone's view events are scope to the view's el. In this case, you've specified the view's el as ALL HTML elements with a class of "accordion". Therefore, when you click on any of your HTML elements with this class, the code runs for all of them, which is why you are seeing this behavior.

This article will show you a few options for doing what you want, correctly:

  • Backbone.js: Getting The Model For A Clicked Element

I would also recommend reading this one, to better understand the use of el in Backbone, and a few of the tricks and traps of it:

  • Backbone.js: Object Literals, Views Events, jQuery, and el
like image 102
Derick Bailey Avatar answered Nov 15 '22 05:11

Derick Bailey