Milkmannetje
Milkmannetje

Reputation: 1182

Can't use jQuery function inside Object Literal

I'm trying to learn how the object literals pattern works in Javascript. In one of my projects i'm stuck on a part where I use some jQuery functions. For the sake of the problem I build a little example.

I hope someone can provide me with some awesome hints.

Javascript: creating an object literal, and calling the init() method.

HTML: Some parts with a remove button. When clicked, I want to display an alert with the associated id extracted as data-attribute from the DOM. But there is the part it is failing, javascript does not know what .data means in that specific function.

Thanks... !

var test = {
  init: function() {
    this.dom();
    this.events();
  },
  dom: function() {
    this.$contentbox = $('.box');
    this.$buttons = this.$contentbox.find('a');
  },
  events: function() {
    this.$buttons.on('click', this.removeDiv);
  },
  removeDiv: function(event) {
    event.preventDefault();
    var div = this.closest('.removeMe'); // This works perfectly
    var divID = div.data('id'); // Crashing -> Uncaught TypeError: div.data is not a function
    alert('Product ' + divID + ' is to be deleted...');
  }
}

test.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box">
  <div class="content">
    Hi there! Click X to delete item :)
  </div>
  <div data-id="6" class="removeMe">
    Product 6 <a href="#">(X)</a>
  </div>
  <div data-id="7" class="removeMe">
    Product 7 <a href="#">(X)</a>
  </div>
  <div data-id="8" class="removeMe">
    Product 8 <a href="#">(X)</a>
  </div>
</div>

Upvotes: 2

Views: 1241

Answers (1)

Alex K.
Alex K.

Reputation: 175916

div is a vanilla HTMLDivElment not a jQuery object so has no .data() method, instead:

var divID = $(div).data('id')

Upvotes: 2

Related Questions