0

I am connecting a datatable from datatables.net with my Angular app where I am trying to get data fra a row in typescript. I can see the data through the console, but I can't reach my other methods in the class.

So i tried to .bind(this) on the table.on() method but did not help.

var table = $('#datatable').DataTable();

// Edit record
  table.on('click', '.edit', function() {
    let $tr = $(this).closest('tr');
    var data = table.row($tr).data();
    console.log(data[0]);
    this.navigateTo(data[0]);
  }.bind(this));

But i receive following error:

ERROR TypeError: Cannot read property '0' of undefined

So I need a symbol from data from data[0] to pass on to another component. But then this error shows.

What am I doing wrong? I guess it is something with the .bind(this), but i am not sure.

Thanks in advance.

1 Answer 1

1

The problem is that the event handling in jQuery relies on changing the this in the scope of the function. When you attach the click event handler to .edit, jQuery will try to call the handler passing the clicked DOM element as this. That is necessary for your code cause you are using the clicked element in $(this).closest('tr');.

When you add .bind(this) you prevent jQuery from "replacing" the this when calling the handler. In this case this will be the same as it was when .bind(this) was called.

There are a few ways you can workaround this situation:

  1. Create a reference to the outer this:

    var table = $('#datatable').DataTable();
    var that = this;
    
    // Edit record
      table.on('click', '.edit', function() {
        let $tr = $(this).closest('tr');
        var data = table.row($tr).data();
        console.log(data[0]);
        that.navigateTo(data[0]);
      });
    
  2. Keep the binding, but use the event target instead of this:

    var table = $('#datatable').DataTable();
    
    // Edit record
      table.on('click', '.edit', function(event) {
        let $tr = $(event.target).closest('tr');
        var data = table.row($tr).data();
        console.log(data[0]);
        this.navigateTo(data[0]);
      }.bind(this));
    
  3. Use arrow function to keep the outer this, and get the clicked element from the event:

    var table = $('#datatable').DataTable();
    
    // Edit record
      table.on('click', '.edit', event => {
        let $tr = $(event.target).closest('tr');
        var data = table.row($tr).data();
        console.log(data[0]);
        this.navigateTo(data[0]);
      });
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thiago. Thanks for your help and great answer. Everything is good now! :) Went with option number 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.