Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Backbone.js Event Binding

I'm using Backbone.js have a segmented control-type UI element for each model's view. They are each made up of a ul with a few li elements. I want to bind an event such that when one of these elements is clicked, I can determine which one has been clicked and update the model with the appropriate value.

The problem is that Backbone binds the events (these are in the events hash of the view) such that "this" in the callback function refers to the view, not the li elements. This means that I can not determine which of the several li elements has been clicked. If I used a normal jQuery binding, I can have "this" bound to the li elements, but then I don't have track of the model anymore, so I can't update it.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

jQuery's habit of setting this to whatever happens to be convenient at the time is a pretty nasty pattern, in my opinion -- fortunately, you never have to rely on it:

onClick: function(e) {
  this;                // Still the view instance (as it should be).
  e.target;            // The element that was clicked.
  e.currentTarget;     // The element that was bound by the click event.
}

... You can use the target or currentTarget of the event object, as appropriate.

over 4 years ago · Santiago Trujillo Relatório

0

Can't figure out why I can't comment on @jashkenas answer above. His method is correct (thank you!) but I thought I'd clarify the situation: in your event handler, you can recover the element that the event was bound to. Sample backbone code would look like this:

MyView = Backbone.View.extend({
    events: {
        'click .item': 'handleClick'
    },

    handleClick: function(e) {
        this; // The view instance
        e.target; // The element that was clicked 
        e.currentTarget; // The element that was bound by the click event
    }
});

I use this to setup default text in all of my form fields...yeah I'm not much into HTML5 yet :)

Edit: Btw, e.target is the raw element. You'll need to use $(e.target) to get jQuery access.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda