javascript - Create Jquery Plugin with dynamic parameters for MULTIPLE usage -


i creating jquery plugin, looks :

(function ( $ ) {      // -- person object used 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        // -- jquery fn function     $.fn.myplugin = function(options) {         // here 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 above plugin used many elements different situation :

<div class="jumbotron content">    <p class="something-one">one</p>    <p class="something-two">two</p> </div>  <script>    // call plugin parameters    $('.something-one').myplugin({person_name: 'mother'});    // result wrong : father (should mother)     // call plugin without parameters    $('.something-two').myplugin();    // result correct : father </script> 

the parameters not work expected.

all element using plugin receive same parameters last element call

how fix problem :(

you seeing same value because of below click handler

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

$('.content').on('click', '.btncok', .... not delegate event expected. instead attach event tpl directly.

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

here demo http://jsbin.com/jafulo/edit?js,output


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -