3

Let's say I have a jQuery function like this:

$.fn.foo = function(param, callback) {
    if (typeof callback === 'function') {
        callback(params);
    }
}

and then when calling the function on an element like:

$('table tr').foo(bar, function(param) {
    console.log($(this)); // this needs to reference 'table tr'
});

In cases like this, I've noticed that this references the window. How would you reference the element that the function is being called on without passing it as an argument inside the callback?

3
  • To be honest this seems like a strange approach for a plugin method. What is your specific use case? Commented Nov 28, 2019 at 17:31
  • I wanted to submit the closest form when a table tr is double clicked, or if there's no form, just a button, to be able to specify in callback @charlietfl Commented Nov 28, 2019 at 17:33
  • Ok...just need to realize that you won't be able to isolate specific row instances doing it this way since this inside the plugin is jQuery object with all rows in it Commented Nov 28, 2019 at 17:35

1 Answer 1

4

To achieve this you can use call() to set the scope of the function you invoke.

Also note that your $.fn.foo function definition requires two arguments, not one. I used the first one as the classname to apply to the element in this example.

$.fn.foo = function(params, callback) {
  if (typeof callback === 'function') {
    callback.call(this, params);
  }
}

$('table tr').foo('foo', function(classname) {
  $(this).addClass(classname);
});
.foo { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Foo</td>
  </tr>
</table>

Sign up to request clarification or add additional context in comments.

Comments

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.