javascriptjquerybackbone.jsbackbone-viewsjquery-click-event

In Backbone how to get click event on an anchor tag within a list item


In a backbone view within the render function I have an anchor tag with a list item inside a unordered list. in short

var DemoView = Backbone.View.extend({
  el: '#body',
  
  render: function() {
    this.$('sidebar-nav > ul').append($('<li class="divider"></li>'));
    this.$('.sidebar-nav > ul')
      .append($('<li><a href="' + _.path(Overture.contextPath, '/calendars/', 
    this.controller.model.id,'/preview') + '" class="internal-link">Link 1</a></li>'));
    this.$('.sidebar-nav > ul')
        .append($('<li><a href="#" class="internal-link">Link 2</a></li>'));
  } 
});

I want to open an alert box on the click on Link 2 without navigating to some other page.


Solution

  • You can setup the View's events:

    var DemoView = Backbone.View.extend({
      el: '#body',
      events: {
        'click .alert-link': onAlertLinkClick
      },
      onAlertLinkClick: function() {
         // put your alert code here
      },
      render: function() {
        this.$('sidebar-nav > ul').append($('<li class="divider"></li>'));
        this.$('.sidebar-nav > ul')
          .append($('<li><a href="' + _.path(Overture.contextPath, '/calendars/', 
        this.controller.model.id,'/preview') + '" class="internal-link">Link 1</a></li>'));
        this.$('.sidebar-nav > ul')
            .append($('<li><a href="#" class="internal-link alert-link">Link 2</a></li>'));
      } 
    });
    
    

    You have to add the alert-link to the second anchor to select it of course.

    See docs for more info.