3

I am currently creating a JQuery Plugin that support data-attributes for defining options. I scoured the internet for sources on how to propery do it, but cannot find any.

What I have done so far:

HTML:

 <table id="myTable" data-columns='[{ "header": "Header1" },
                { "header": "Header2" },
                { "header": "Header3" }]'>
    </table>

Plugin:

 $.fn.myPlugin = function () {
        columns:""

    }
    var self = $(this)
    var foo = self.data("columns")

    //..some code to create columns

Plugin Usage:

$("#myTable").myPlugin()
2
  • You don't have to do anything; jQuery already understands the attributes, and will in fact parse them for you. That self.data() call will return an array of objects. Commented Nov 24, 2022 at 0:54
  • Also, in a plugin (unlike a callback to a jQuery method), you don't have to write $(this), because this will point to the jQuery object and not an individual element. In fact, the standard practice for a plugin that could operate meaningfully on more than one matched element in the jQuery object should use a .each() loop, and also of course return the jQuery object as its result so that it can be used in a call chain. Commented Nov 24, 2022 at 0:56

1 Answer 1

2

Here is a minimal jQuery plugin based on your question.

(function( $ ) {
    $.fn.myPlugin = function () {
        this.filter('table').each(function() {
            var container = $(this);
            var data = container.data('columns');
            var html = '<tr>'
               + data.map(obj => '<th>' + obj.header + '</th>').join('')
               + '</tr>';
            console.log('html: '+html);
            container.append(html);
        });
        return this;
    }
}( jQuery ));

$('#myTable').myPlugin()
#myTable th {
  border: 1px gray solid;
  padding: 1px 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" data-columns='[{ "header": "Header1" },
    { "header": "Header2" },
    { "header": "Header3" }]'>
  </table>

Note the .filter('table'), which makes sure the code is only applied to tables.

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.