2011-08-09 3 views
2

J'ai un plugin de curseur d'image que j'ai fait que je veux étendre certaines des fonctionnalités de. Je voudrais faire en sorte que vous pouvez appeler la méthode suivante en appelant ce qui suit comme le fait jQuery UI:Plugin jQuery - appelant une fonction/méthode publique

$("#elemID").imageSlider("next");

Je suis un peu à une perte sur la façon d'y parvenir. Voici ce que j'ai jusqu'ici avec certains des entrailles manquantes pour l'espace.

(function($) { 
$.fn.imageSlider = function (options) { 
    var options = $.extend({}, $.fn.imageSlider.defaults, options), 
     obj = $(this),       // Set it here so we only look for it once 
     objID = obj.attr('id'), 
     sliderName = objID + '_slider', 
     total = 0, 
     counterID = objID + '_ct'; 

    // Private Methods 
    var initialize = function() {   
     if (options.jsonObject === null) { 
      processAjax(); 
     } else { 
      process(options.jsonObject); 
     } 

     return obj; 
    } 

    // Executes an AJAX call 
    var processAjax = function() { 
     $.ajax({ 
      url: options.jsonScript, 
      type: 'GET', 
      data: options.ajaxData, 
      dataType: 'json', 
      success: function (data) { 
       process(data); 
      }, 
      complete: function (jqXHR, textStatus) { 
       if (options.onComplete !== $.noop) { 
        options.onComplete.call(); 
       } 
      } 
     }); 
    } 

    var process = function (data) { 
     // Generates the HTML 
    } 

    var changeImage = function (me, target, ops) { 
     //rotate the image 
    } 

    $.fn.imageSlider.next = function (elemID) { 
     // Currently how I call next on the slider 
    } 

    return initialize(); 
} 


$.fn.imageSlider.defaults = { 
    // options go here 
    } 
})(jQuery) 

Répondre

1

La méthode standard pour le faire (see docs) est de créer un objet appelé methods avec les magasins chacun de vos méthodes par son nom, et l'extension réelle recherche le la méthode à appeler par son nom et l'exécute. J'aime ...

(function($){ 

    var methods = { 
    init : function(options) { // THIS }, 
    process : function() { // IS }, 
    changeImage : function() { // GOOD }, 
    next : function(content) { // !!! } 
    }; 

    $.fn.imageSlider = function(method) { 

    // Method calling logic 
    if (methods[method]) { 
     return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.imageSlider'); 
    }  

    }; 

})(jQuery); 
+0

Merci! Je dois avoir regardé cela un million de fois et ne l'ai jamais réalisé. – tomoguisuru

Questions connexes