Not able to catch a on-click event on an <a> href with Backbone's Events function

528 Views Asked by At

I am not able to catch onclick events in the events object in backbone. I am using the link_to in rails to generate the <a> link. Can someone help me out here?

HTML :

<div id="flash-messages">
<ul>
<li style="opacity: 1;">
<li style="opacity: 1;">
<li style="opacity: 1;">
<div class="alert alert-info">
<a id="consent-link" href="#">See here for more informationnn.</a>
<a class="controls close" aria-hidden="true" data-dismiss="alert" href="#">
<i class="icon-cancel fontLoaded"></i>
</a>

JS code:

    module.exports = View.extend({
 
   template: template,
   events: {
    'click #btnSubmitModal': 'saveConsent',
    'click #consent-link' : 'openConsent'
   },

   openConsent: function(event){
    event.preventDefault();
    console.log ("asaasagsgsgs");
    view = new modalView({model: this.model})
   },
1

There are 1 best solutions below

0
T J On

From the docs:

template view.template([data])

While templating for a view isn't a function provided directly by Backbone, it's often a nice convention to define a template function on your views. In this way, when rendering your view, you have convenient access to instance data. For example, using Underscore templates:

var LibraryView = Backbone.View.extend({
    template: _.template(...)
});

So template is a custom property that we can use to point to a template function. Defining this isn't enough, you have to create the actual template by passing the data to template function and append the resulting HTML to the views element.

Something like:

 module.exports = View.extend({
  initialize: function(){
    this.render();
  },
  template: Handlebars.compile(template), // where template is the handle bars template
  events: {
   'click #btnSubmitModal': 'saveConsent',
   'click #consent-link' : 'openConsent'
  },
  render: function(){
    this.$el.append(this.template(data)); //where data is the data you wish to pass to handle bars template function
  },
  openConsent: function(event){
    event.preventDefault();
    console.log ("asaasagsgsgs");
    view = new modalView({model: this.model})
  }
 });

The event handlers are scoped to (delegated to ) the view's element. Once you append the HTML to the view's element (as shown in the render method of above example) the events will start working.