Really basic jquery plugin template - with callback


/ Published in: JavaScript
Save to your folder(s)

This is a really basic skeleton template for jQuery plugins. It provides a callback function which can be called anywhere in your plugin with base.success(); This will return the current element, but you can pass anything you like back by changing the base.$el value passed to the function to whatever you like.


Copy this code and paste it in your HTML
  1. /* Plugin code */
  2. (function($){
  3. $.pluginName = function(el, option, callback){
  4.  
  5. /* Setup base elem vars */
  6. var base = this;
  7. base.$el = $(el);
  8. base.el = el;
  9. base.$el.data("pluginName", base);
  10. /* Option object */
  11. base.o = option;
  12.  
  13. /*
  14.   * Init
  15.   */
  16. base.init = function () {
  17.  
  18. };
  19.  
  20. /*
  21.   * Callback func when successful (returns element)
  22.   */
  23. base.success = function() {
  24. callback(base.$el); // Return elem
  25. };
  26.  
  27. base.init();
  28. };
  29. $.fn.pluginName = function(option, callback){
  30. return this.each(function(){
  31. (new $.pluginName(this, option, callback));
  32. });
  33. };
  34. })(jQuery);
  35.  
  36. /* Use plugin */
  37. $(document).ready(function () {
  38.  
  39. $(document).pluginName(100, function(elem) {
  40. // Success
  41. console.log("Success");
  42. });
  43.  
  44. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.