Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to add methods to jQuery objects than .data()?

Tags:

jquery

I want to add a custom method to a specific jQuery object:

$('#DOMelement').customFunc(param); // not a reality

Currently, I have:

var customFunc = function(param) { 
    // do something special
}
$('#DOMelement').data('customFunc', customFunc);

Which I then call, like:

var cF = $('#DOMelement').data('customFunc');
cF(param);

All of this works, but it's a pain. Is there a better solution? Other than writing an extensive plugin?

like image 513
peter Avatar asked Feb 17 '11 00:02

peter


1 Answers

It sounds like think what you want to do is make a plugin. It's not really extensive at all. Taken from http://docs.jquery.com/Plugins/Authoring, you can just do:

(function( $ ){
    $.fn.myPlugin = function() {

        // Do your awesome plugin stuff here

    };
})( jQuery );

Then calling it is simple:

$('#DOMelement').myPlugin();

I don't believe you should be putting custom functions in the "data" property. The data property was built with the intention of embedding custom non-visible data to your HTML. While I guess you could put functions in there, I'm not sure that's compliant. Also, all of your JavaScript code will then be embedded in your HTML element.

(Taken from http://dev.w3.org/html5/spec/Overview.html#embedding-custom-non-visible-data-with-the-data-attributes)

Authors can include data for inline client-side scripts or server-side site-wide scripts to process using the data-*="" attributes. These are guaranteed to never be touched by browsers, and allow scripts to include data on HTML elements that scripts can then look for and process.

Here's another article on using data: http://www.marcofolio.net/webdesign/html5_data-_attributes_are_great_and_you_know_it.html

like image 93
Pandincus Avatar answered Oct 11 '22 16:10

Pandincus