Search code examples
javascriptjquerypluginsmakefileconflict

Reuse jquery plugin without conflict


I have a little plugin working as a progressbar. the problem is: I can't update progressbar's value because every change I made, affect just the last object created =(

also.. if I call it as: $(node-selector).progBar().setValue() it works calling the correct node but it loss the config object

follow the code:

	var elm1;
	var elm2;

	$(function($){

		$.fn.progBar = function ( config ){

			if ( typeof ( config ) === "string" ) {
				config = {'text':config} ;
			}

			var config = $.extend ({
				'text' : false
			}, config );

		    return this.each(function( ){

				var $this       = $(this); // $this is the main element

				$this.css("width","200px")
				$this.css("padding","4px 10px")
				$this.css("text-align","center")
				$this.css("background","#eee")
				$this.css("font-weight","bold")
				$this.css("border","1px solid #00F")
				$this.html(config.text)

				$.fn.setValue = function ( newValue ) {
					$this.html(config.text + " " + newValue)
				};

		    });

		};

		elm1 = new $("#elm1").progBar("this is the first...")
		elm2 = new $("#elm2").progBar("this is the seccond...")

		// both lines below just affect the #elm2 object
		elm1.setValue("first")
		elm2.setValue("seccond") // this will overrite line above

	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<div id="elm1" ></div>
<div id="elm2" ></div>


Solution

  • The return this.each... was causing the problem - you were reassigning the setValue function for all instances created with the progBar method. This update should get you going the right direction:

    var elm1;
    var elm2;
    
    $(function($) {
    
      $.fn.progBar = function(config) {
    
        if (typeof(config) === "string") {
          config = {
            'text': config
          };
        }
    
        var config = $.extend({
          'text': false
        }, config);
    
        this.css("width", "200px")
        this.css("padding", "4px 10px")
        this.css("text-align", "center")
        this.css("background", "#eee")
        this.css("font-weight", "bold")
        this.css("border", "1px solid #00F")
        this.html(config.text)
        this.setValue = function(newValue) {
          var currentInnerText = this.html();
          this.html(currentInnerText + " " + newValue)
        };
        return this;
      };
    
    
    
      elm1 = new $("#elm1").progBar("this is the first...");
      elm2 = new $("#elm2").progBar("this is the seccond...");
    
      // both lines below just affect the #elm2 object
      elm1.setValue("first");
      elm2.setValue("seccond"); // this will overrite line above
    
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    
    <div id="elm1"></div>
    <div id="elm2"></div>