javascriptjquerybackbone.jsdom-eventsbackbone-events

Triggering an event on el in Backbone View


I have a view that creates and populates a Selectlist. I want to bind an event on the Change event (When the user selects a different Option.

It simply outputs something close to this:

<select>
   <option value="id">ID Name</option
</select>

The View:

App.Views.SessionList = Backbone.View.extend({
   tagName: 'select',
   id: 'sessionList',
   events: {
       'change': 'selectionChanged'
   },
   initialize: function () {
       // Load Collection
       _.bindAll(this, 'selectionChanged');

       this.template = _.template($('#optionsTemplate').html());
       this.Sessiontemplate = _.template($('#session_template').html());
       this.SelectedSessiontemplate = _.template($('#selected_session_template').html());

       // Create Collection
       this.SessionList = new App.Collections.SessionList();

       // Set Bindings
       this.SessionList.bind('add', this.addSession, this);
       this.SessionList.bind('reset', this.addSessions, this);


       this.render();

       this.SessionList.fetch();
   },
   render: function () {

       return this;
   },
   addSession: function (item, num) {
       if (num === 0) {
           $(this.el).append(this.SelectedSessiontemplate(item.toJSON()));
           console.log("Selected");
       }
       else {
           $(this.el).append(this.Sessiontemplate(item.toJSON()));
       }
   },
   addSessions: function () {
       var self = this;
       // Add all Rows
       for (var i = 0; i < self.SessionList.models.length; i++) {
           this.addSession(self.SessionList.models[i], i);
       }
   },
   selectionChanged: function (e) {
       var field = $(e.currentTarget);
       var value = $("option:selected", field).val();
   }
});

The Session Template is just simply:

<option value="{{Id}}">{{Name}}</option>

The event never gets triggered, and It seems that it isn't getting binded correctly. I want to trigger it on the change of the select list.

I originally thought I may be having an issue similar to: backbone.js events and el, however it doesn't work in this case.


Solution

  • It is hard to debug your problem directly, because we don't have all of the information (what does SessionList look like... the templates, etc).

    BUT, I have paired down your example to some code where the event does, indeed work. Hopefully, you can build it up from there? You can fork the jsFiddle if you want to get to a place where it fails for you and we can try to help further.

    window.App = { Views: {} };
    
    App.Views.SessionList = Backbone.View.extend({
        tagName: 'select',
    
        events: {
            'change': 'selectionChanged'
        },
    
        initialize: function () {
            _.bindAll(this, 'selectionChanged');
            this.render();
        },
    
        render: function () {
            $(this.el).append('<option value="foo">Option 1</option>');
            $(this.el).append('<option value="bar">Option 2</option>');                
            return this;
        },
    
        selectionChanged: function (e) {
            var value = $(e.currentTarget).val();
            console.log("SELECTED", value);
        }
    });
    
    var view = new App.Views.SessionList();
    $("body").append(view.el);
    

    Given that code, you will get a console log with the value every time you select an item.

    Since you aren't getting that, I am guessing you are seeing an exception or something like that? Does your debugger give you any hints?

    Good luck!