Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the jQuery element (or attributes) in a click event in Backbone.js?

Tags:

I have the following code:

HTML:

<div id='example'>  <a href='#' data-name='foo' class='example-link'>Click Me</a>  <a href='#' data-name='bar' class='example-link'>Click Me</a> </div> 

JavaScript

example_view = Backbone.View.extend({     el: $("#example"),     events: {       'click .example-link' : 'example_event'     },     example_event : function(event) {       //need to get the data-name here     }  }); 

how can I get the data-name attribute of the link that was clicked inside of the example_event function ?

like image 696
GSto Avatar asked May 09 '12 14:05

GSto


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

How do you find the ID of the view by which the event method is triggered?

You can use event.target.id in event handler to get id of element that fired an event.

What are jQuery attributes?

jQuery attribute methods allows you to manipulate attributes and properties of elements. Use the selector to get the reference of an element(s) and then call jQuery attribute methods to edit it. Important DOM manipulation methods: attr(), prop(), html(), text(), val() etc.


2 Answers

Try this.

example_event : function(event) {   //need to get the data-name here   var name = $(event.target).data('name'); }  
like image 66
ShankarSangoli Avatar answered Sep 27 '22 17:09

ShankarSangoli


You can also do this without jQuery using JavaScript's getAttribute method:

example_event : function(event) {   //need to get the data-name here   var name = event.target.getAttribute('data-name'); }  
like image 26
tomsabin Avatar answered Sep 27 '22 16:09

tomsabin