Trigger an event on ale in Backbone View mode

I have a view that creates and populates Selectlist. I want to associate an event with a Change event (when the user selects another option.

It simply outputs something close to this:

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

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 simple:

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

The event never fires, and it seems that it is not getting the binding correctly. I want to call it when changing the selection list.

Initially, I thought I might have a problem like: backbone.js events and el , however in this case it does not work.

+5
source share
1 answer

, ( SessionList... ..).

, - , , . , ? jsFiddle, , , .

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);

.

, , - ? - ?

!

+6

All Articles