google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






R?utiliser les codes JavaScript jQuery Plugins : tutoriels et des exemples L' autre objectif de ce tutorial JavaScript article il est pour nous guider ?tape par ?tape pour construire un plug-in pour framework jQuery en r?utilisant les vieux codes source JavaScript ou vous pouvez ?crire de nouveaux A partir de cette JavaScript tutorial , vous apprendrez comment cr?er un formulaire de jQuery plug -in , s'il vous pla?t aller ? la page int?rieure post pour des instructions compl?tes , des commentaires et des exemples de code JavaScript


�tiquette: R?utiliser les codes JavaScript, construire jQuery Plugin, ?tape par ?tape, vieux code source JavaScript

G�n�rez vos vid�os d'entreprise par l'IA avec la voix ou simplement du texte



Votre premi�re application vid�o AI GRATUITE ! Automatisez votre premi�re vid�o AI. Cr�ez votre vid�o professionnelle en 5 minutes gr�ce � l'IA. Aucun �quipement ni comp�tence en montage vid�o requis. Production vid�o sans effort pour les sp�cialistes du marketing de contenu.
Application vid�o AI ILLIMIT�E gratuite � port�e de main

Adding Chaining

If you are not returning a specific value from your function, with only a small tweak you can gain the benefit of being able to have your utility chained together with other jQuery code. Such plugin chains are often used to accomplish complex actions easily and efficiently.

The trick is to simply return the “this” value that contains the wrapped set:

  (function($){

    $.fn.redAlert = function(badValue) {
      return this.each(function() {

        if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)

           $(this).addClass('error').css('background-color', 'red');
      });

    };
  })(jQuery);

So I can then construct a chain of calls:

$("form input:text").redAlert('Stink').addClass('scanned');

But Where is the Namespacing?

You may have noticed that we skipped an important step when implementing our redAlert plugin. It isn’t namespaced.

Simply pushing our function into a sub-object, like we did for our readCookie utility plugin won’t work:

(function($){
  // BAD, THIS WON'T WORK
  $.fn.webvantaUtils = {};

  $.fn.webvantaUtils.redAlert = function(badValue) {
    return this.each(function() {

      if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)

        $(this).addClass('error').css('background-color', 'red');
    });

  };
})(jQuery);

When doing so, we lose access to the wrapped set contained in the initial “this” variable. It instead points to the webvantaUtils object, not the wrapped set.

To get around this issue, the jQuery recommendation is to organize all of your plugin methods within an object literal, then use a dispatcher technique to access the desired functions:

(function( $ ){

  var methods = {
    init : function( options ) { },

    redAlert : function(badValue) {
      return this.each(function() {

        if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)

          $(this).addClass('error').css('background-color', 'red');
      });

    }
  };
  $.fn.webvantaUtils = function( method ) {

    // Method dispatch 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.webvantaUtils' );
    }

  };
})( jQuery );

And then call it via:

$("form input:text").webvantaUtils('redAlert','Stink').addClass('scanned');

This approach is a little more complicated, but ensures that the namespace is “clean”. It uses a few JavaScript tricks to accomplish its goal. First, the actual functions of our plugin are stored as attributes of the literal object called “methods”. Second, the entry point to our plugin is the “namespace”, here “webvantaUtils”.

When we invoke the plugin through this entry point, it first checks to see what kind of parameters were passed in. That may sound odd, since it looks like the entry point only takes one named parameter “method”. Regardless of the number of named arguments, JavaScript doesn’t complain if “extra” parameters are passed in.

The expectation is that the first parameter will either be nothing at all, an object of some kind, or a string naming the desired function.

First the entry point tries to use the value of “method” to find a matching attribute of the “methods” object. If that fails, it next checks to see if “method” is itself an object OR it is a null or undefined value. In that case, with our sample above, an optional “init” method is invoked. This is purely convention, and could be stripped out if you don’t need to initialize anything. “init” is a handy place if you have default values you need to set up or override.

If none of the previous conditions are true, then an error message gets displayed in the console.

Now, in the case of both the init function or a matched function name being found in the methods object, the code uses the JavaScript apply() method. apply() is a method on the Function object. apply()’s job is to execute the receiver’s function, and it uses its first parameter to set what the value of “this” will be inside of that function. The second parameter is an array which is passed to the called function as its parameter list.

Here we see the special Argument object being used in the variable called “arguments”. JavaScript always sets “arguments” to contain the complete parameter list of a called function. In this case, it is used to pass on any parameters sent to the entry point (other than the first one in the case of a name string being passed in to invoke a plugin function).

This may be slightly confusing, yet digging in to the JavaScript is educational. The good news is that you can focus on using this “plugin pattern” as a template for your own code and mostly ignore the rest of the details when getting started.

The jQuery Plugin Authoring guidelines contain even more examples.

UI Widget Factories

While we won’t get in to the details here, we should point out that if you are trying to build user interface code, or need to construct more complicated, statefull plugins, a worthwhile plugin architecture to review is the jQuery UI Widget factory mechanism. Widgets provide additional conventions for organizing code including dealing with defaults and options on a per widget basis, code hiding of “private” functions used by the widget, and ways of exposing widget data accessors, events, and other functionality.

A Wrap of Plugins

We’ve briefly explored the basics that will permit you to clean up and possibly refactor your existing JavaScript code into reusable jQuery plugins. With the information presented in this article, and the Plugin Authoring notes on the jQuery.org site, you should have all you need to get started. Next time, we will take a peek at a relatively new client-side storage technology that has come out of the HTML5 efforts and build a small jQuery plugin that wraps it with a generic API.

AIVideo-App.com
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte

chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle

AppAIVidéo
Votre première application vidéo AI GRATUITE

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app

Your next top AI Assistant
Claude AI, developed by Anthropic

Your next top AI Assistant
Claude AI, developed by Anthropic

Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise

Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA

chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle

Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue

Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils

GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet

iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16

Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $

JavaScript par jour


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web