2012-04-17 19 views
8

Este código no tiene mucho contexto, pero ilustrará mi pregunta. Es una vista Backbone definida en un módulo AMD que uso para cargar a través de require.jsAgregar eventos backbone.js después de la inicialización

Esencialmente, quiero poder agregar eventos a una vista Backbone después de que se haya ejecutado la inicialización. En este momento estoy creando un objeto de eventos vacío, y luego en un método llamado addView, agrego un evento cada vez que se llama a la función. Esto no está funcionando actualmente.

No estoy seguro en qué punto se registran los eventos, pero sospecho que de alguna manera tengo que obtener la vista para actualizar sus oyentes cuando cambia el objeto events?

¿Alguien sabe cómo puedo lograr agregar eventos a un Backbone.js después de la inicialización?

define([ 
    'jQuery', 
    'Backbone'], 

    function ($, Backbone) { 

     var contentViews = new Array(); 

     var SlidePanelView = Backbone.View.extend({ 

      events: {}, 

      /// <param name="targetDataAtt">The unique value inside the target's Data-Slide-Panel-Id attribute</param> 
      /// <param name="event">Backbone event to trigger view</param> 
      /// <param name="destroyOnRemove">True to destroy view when removed, False otherwise (Default true)</param> 
      addView: function (targetDataAtt, event, view, destroyOnRemove) { 
       destroyOnRemove = typeof destroyOnRemove !== 'undefined' ? destroyOnRemove : true; 

       this.events[event] = "viewEventFired"; 
       contentViews[targetDataAtt] = { View: view, DestroyOnRemove: destroyOnRemove }; 
      }, 

      viewEventFired: function (e) { 

       var target = $(e.target); 
       var id = target.attr('data-slide-panel-id'); 
       console.log(id); 
      } 

     }); 

     // Return a singleton?? 
     return new SlidePanelView; 


    }); 

Respuesta

11

Si estoy entendiendo correctamente la pregunta, después de agregar eventos adicionales para el hash eventos, llame delegateEvents() en la idea de volver a enlazar eventos.

addView: function (targetDataAtt, event, view, destroyOnRemove) { 
     destroyOnRemove = typeof destroyOnRemove !== 'undefined' ? destroyOnRemove : true; 
     this.events[event] = "viewEventFired"; 
     this.delegateEvents(); 
     contentViews[targetDataAtt] = { View: view, DestroyOnRemove: destroyOnRemove }; 
    } 

No desenlaza todos los enlaces de eventos existentes y vuelve a enlazar todos los eventos en los eventos picadillo de nuevo, y no estoy seguro de los problemas de rendimiento subyacentes de hacer eso, pero es algo a tener en cuenta.

Cuestiones relacionadas