The clickbone click event fires events for the entire collection, not the model

I can’t understand what happened. When I click on the model name, it selects all the models in the collection at once, and does not select one model. If I translate this event from logView to logsView, it works correctly, but does not have access to the model, I can find this model using an index or ant with a different model identifier, but I do not think this is a good 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"}); 
+7
source share
1 answer

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

Display modes in the layout are the scope of el . In this case, you specified the el view as ALL HTML elements with the accordion class. Therefore, when you click on any of your HTML elements with this class, the code runs for all of them, so you see this behavior.

In this article you will find several options for the correct execution:

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

+10
source

All Articles