Posted By

rickygri on 11/15/13


Tagged

template jquery


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

hawk007


jQuery Plugin template


 / Published in: JavaScript
 

URL: http://markdalgleish.com/2011/05/creating-highly-configurable-jquery-plugins/

Uses the object prototype to extend data. Instantiate as an object and use as specified below (bottom of the code)

  1. /*
  2.  * Plugin template
  3.  */
  4. (function(window, $){
  5. var Plugin = function(elem, options){
  6. this.elem = elem;
  7. this.$elem = $(elem);
  8. this.options = options;
  9. };
  10.  
  11. Plugin.prototype = {
  12. defaults: {
  13. message: 'Hello world!'
  14. },
  15. init: function() {
  16. this.config = $.extend({}, this.defaults, this.options);
  17.  
  18. this.displayMessage();
  19.  
  20. return this;
  21. },
  22. displayMessage: function() {
  23. alert(this.config.message);
  24. }
  25. };
  26.  
  27. Plugin.defaults = Plugin.prototype.defaults;
  28.  
  29. $.fn.plugin = function(options) {
  30. return this.each(function() {
  31. new Plugin(this, options).init();
  32. });
  33. };
  34.  
  35. window.Plugin = Plugin;
  36. })(window, jQuery);
  37.  
  38. /*
  39.  * Use plugin
  40.  */
  41. //Set the message per instance:
  42. $('#elem').plugin({
  43. message: 'Goodbye World!'
  44. });
  45.  
  46. var p = new Plugin(document.getElementById('elem'), {
  47. message: 'Goodbye World!'
  48. }).init();
  49.  
  50. //Or, set the global default message:
  51. Plugin.defaults.message = 'Goodbye World!';

Report this snippet  

You need to login to post a comment.