2011-11-04 13 views
5

Tengo una vista que crea y rellena una lista de selección. Quiero unir un evento en el evento Change (Cuando el usuario selecciona una opción diferenteActivación de un evento en el en Backbone View

Simplemente da salida a algo parecido a esto:.

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

La Vista:

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

La plantilla de sesión es simplemente:

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

El evento nunca se desencadena, y parece que no se enlaza correctamente. Quiero activarlo en el cambio de la lista de selección.

Originalmente pensé que podría tener un problema similar al: backbone.js events and el, sin embargo, no funciona en este caso.

Respuesta

6

Es difícil depurar su problema directamente, porque no tenemos toda la información (cómo se ve SessionList ... las plantillas, etc.).

PERO, he emparejado su ejemplo con algún código donde el evento funciona, de hecho funciona. Con suerte, ¿puedes construirlo desde allí? Puede fork the jsFiddle si quiere llegar a un lugar donde le falla y podemos intentar ayudarlo.

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

Dado ese código, obtendrá un registro de la consola con el valor cada vez que seleccione un elemento.

Dado que no está obteniendo eso, ¿supongo que está viendo una excepción o algo así? ¿Su depurador le da alguna pista?

¡Buena suerte!

+0

Tonto, pero Chrome estaba almacenando en caché la página y las actualizaciones no se mostraban incluso después de muchos intentos. Pero utilicé tu violín, lo que me permitió construir y arreglar algunas cosas. ¡Gracias! – Hyper

Cuestiones relacionadas