Create Jquery Plugin with dynamic parameters for MULTIPLE usage

255 Views Asked by At

I creating jquery plugin, looks like this :

(function ( $ ) {

    // -- This is Person Object used for plugin
    var PersonObject = function(elem, options)
    {
       this.elem = elem;
       this.options = options;
       this.run();
    };

    PersonObject.prototype = {

       run: function()
       {
          // console.log(this.options.person_name);
          self = this;
          tpl = '<a class="btn btn-link btncok">one</a>';

          self.elem.after(tpl);

            $('.content').on('click', '.btncok', function(e) {
                e.stopImmediatePropagation();
                self.show();
            });

          return self.options.person_name;
       },

       show: function()
       {
            console.log(this.options.person_name);
       }
    };
    // -- end Person Object



    // -- This is my jquery fn function
    $.fn.myPlugin = function(options) {

       // here is default options
       var default_options = {person_name: 'father'};

       options = $.extend({}, default_options, options);

       return this.each(function() {

          new PersonObject($(this), options);

       });
    };
    // -- end jquery plugin

}( jQuery ));

. .

so then, when the above plugin are used by many elements with different situation like this :

<div class="jumbotron content">
   <p class="something-one">one</p>
   <p class="something-two">two</p>
</div>

<script>
   // call the plugin WITH parameters
   $('.something-one').myPlugin({person_name: 'mother'});
   // result wrong : father (should be mother)

   // call the plugin WITHOUT parameters
   $('.something-two').myPlugin();
   // result correct : father
</script>

the parameters is not work expected.

all the element that using the plugin will receive same parameters by last element call

how to fix this problem :(

1

There are 1 best solutions below

2
On BEST ANSWER

You are seeing the same value because of the below click handler

$('.content').on('click', '.btncok', function(e) {
  e.stopImmediatePropagation();
  self.show();
});

$('.content').on('click', '.btncok', .... is does not delegate event as expected. Instead attach an event to tpl directly. Something like this

this.appendedEl = $('<a class="btn btn-link btncok">'+this.options.person_name+'</a>');
this.elem.after(this.appendedEl);
this.appendedEl.on('click', function(e) { // <--- this way the event is attached to the right element
  e.stopImmediatePropagation();
  this.show();
}.bind(this)); // <--- I used bind instead of self

Here is a demo http://jsbin.com/jafulo/edit?js,output