1

I'm learning a custom plugin of jQuery, And see this in the code:

$.jqPaginator = function (el, options) {
  if (!(this instanceof $.jqPaginator)) {
    return new $.jqPaginator(el, options)
  }

  var self = this

  self.$container = $(el)

  self.$container.data('jqPaginator', self) ...}

And I'm confused why data() is not like $(element).data(name, value) to set data-name to the DOM.

Y.X
  • 61
  • 5

1 Answers1

1

This is an atypical plugin, so if you're studying it for the purposes of understanding plugins in general, look elsewhere.

The data call is storing a reference to the jqPaginator instance in jQuery's data cache for the element passed in as el. That means that later, if given the element, it can get the jqPaginator instance for it (if any) by doing this:

var instance = $(el).data("jqPaginator");
if (instance) {
    // `instance` is an instance of jqPaginator already attached to the element
    // ...
}

Annotated:

// Create a variable for functions to close over that refers to
// the current instance of $.jqPaginator
var self = this

// Store a jQuery wrapper for `el` on the instance
self.$container = $(el)

// Store the instance in the jQuery data cache for `el`
self.$container.data('jqPaginator', self) ...}

The jQuery data cache is storage linked to the element (but not preventing it from being cleaned up if removed from the DOM) where you can store additional information for the element.

Here's a simple example of data at work:

$("input[type=button]").on("click", function() {
    const $btn = $(this);
    const timestamp = $btn.data("timestamp");
    if (!timestamp) {
        console.log("That was the first click of the button, click it again");
        $btn.data("timestamp", new Date());
    } else {
        console.log("That wasn't the first click, the first click was done at " + timestamp.toLocaleTimeString());
    }
});
<input type="button" value="Click Me">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

And I'm confused why data() is not like $(element).data(name, value) to set data-name to the DOM.

data never sets data-* attributes. People sometimes misunderstand the data method, thinking it's a simple accessor for data-* attributes on the element. It isn't. The first time you use it on an element, it seeds the data cache with any values it finds in data-* attribute, but that's all it ever does with them. More here.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875