MurifoX
MurifoX

Reputation: 15089

Dynamically add HTML element with new id to a Backbone View

I have a template with a list <ul> that has 2 <li> with links <a id='variable_id'> with different ids. I've bind the events to this 2 ids iniciais and palavras. The thing is, when i click for an example the iniciais link, i remove it from the <ul> and create a new link with the id='palavras'. The problem is, this new link doesn't have the events binded to it, even though the event is on the events hash. How can i do something like jQuery live or on methods on a Backbone View subelement?

var MyView = Backbone.View.extend({
  el: '#campos',
  initialize: function() {
  },

Notice how i have the events binded to the 2 kinds of links.

  events: {
    'click #palavras': 'mudar_para_consulta_palavras',
    'click #iniciais': 'mudar_para_consulta_iniciais'
  },

In this method, i remove the list item from the list, and insert some new content with the new id.

  mudar_para_consulta_palavras: function() {
    $('#campo_consulta').val('');
    $('#campo_consulta').attr('placeholder', 'Digite palavras inteiras');
    $("#campo_consulta").attr('tipo', 'chave');
    $('#palavras').parent().remove();
    $("<li><a id='#iniciais'>Consultar por Iniciais</a></li>").insertBefore('.divider');
  },

Same thing for this other method, only changes the id definition.

  mudar_para_consulta_iniciais: function() {
    $('#campo_consulta').val('');
    $('#campo_consulta').attr('placeholder', 'Digite inicio de palavras');
    $("#campo_consulta").attr('tipo', 'iniciais');
    $('#iniciais').parent().remove();
    $("<li><a id='#palavras'>Consultar por palavras</a></li>").insertBefore('.divider');
  }
});
return MyView;
});

Upvotes: 1

Views: 402

Answers (1)

jevakallio
jevakallio

Reputation: 35890

I think you simply have small typo in the markup you insert into the DOM:

$("<li><a id='#iniciais'>Consultar por Iniciais</a></li>")

and

$("<li><a id='#palavras'>Consultar por palavras</a></li>")

Should not have the # character in the id attribute.

Upvotes: 2

Related Questions