2013-07-19 32 views
0

我在寻求帮助。我几乎干净的jQuery样板在这里我的代码:jQuery插件 - 多实例化

http://jsfiddle.net/XXw5h/7/

;(function ($, window, document, undefined) { 


    var pluginName = "defaultPluginName", 
     defaults = { 
      propertyName: "value" 
     }; 

     function Plugin(element, options) { 
     this.element = element; 


     this.options = $.extend({}, defaults, options); 

     this._defaults = defaults; 
     this._name = pluginName; 

     this.init(); 
    } 

    Plugin.prototype = { 

     someVal: Math.round(Math.random() * 99999999), 

     init: function() { 
      self = this; 

      aEl = $('<a/>', { 
       href: '#', 
       text: this.options.propertyName, 
       click: function(e){self._clicked();} 
      }); 

      $(".el1").before(aEl);  
      $(".el1").before("<br/>");  

     }, 

     _clicked: function(el, options) { 
      alert("Random value of el instance:" + this.someVal); 
      alert("Property name:" + this.options.propertyName); 
     } 
    }; 


    $.fn[pluginName] = function (options) { 
     return this.each(function() { 
      if (!$.data(this, "plugin_" + pluginName)) { 
       $.data(this, "plugin_" + pluginName, new Plugin(this, options)); 
      } 
     }); 
    }; 

})(jQuery, window, document); 

$('.el1').defaultPluginName({ 
    propertyName: 'el1 link ' 
}); 

$('.el2').defaultPluginName({ 
    propertyName: 'el2 link' 
}); 

我的问题是,我需要多个实例,它就是我的麻烦开始了。我知道我的问题是在这里找到答案:

jQuery plugin multiple instantiation

,但我不能让它工作。

当你点击链接jsfiddle的el1链接时,我需要显示一个随机数和插件的第一个实例的属性。当你点击链接的jsfiddle的el2链接时,我需要显示第二个随机数和插件第二个实例的属性。目前这两个链接都是一样的。

我的问题是如何为我的插件的每个实例创建自己的选项?然后,创建我自己的每个实例变量的正确方法是什么?谢谢!

+0

嗯,我没有看到任何一个环节,你可以仔细检查你的小提琴? –

+0

Awww,抱歉,并感谢您的留言。更新,现在它应该工作:) – user2595304

回答

1
self = this; 
aEl = $('<a/>', { 
    href: '#', 
    text: this.options.propertyName, 
    click: function(e){self._clicked();} 
}); 

你分配到全球变量self这里,这将是第二个插件实例被覆盖,只有参考它。

添加var keyword使其成为局部变量。

1

Bergi的回答是错误的,您应该将self定义为局部变量。另外,我想补充一点,你应该让someVal每次点击链接时都有一个随机数的函数,否则在初始时它们会是相同的数字。所以更新的代码应该是:

Plugin.prototype = { 

    someVal: function() { 
     return Math.round(Math.random() * 99999999) 
    }, 

    init: function() { 
     var self = this; 

     aEl = $('<a/>', { 
      href: '#', 
      text: self.options.propertyName, 
      click: function (e) { 
       e.preventDefault(); 
       self._clicked(); 
      } 
     }); 

     $(".el1").before(aEl);  
     $(".el1").before("<br/><br/>");  

    }, 

    _clicked: function(el, options) { 
     alert("Random value of el instance:" + this.someVal()); 
     alert("Property name:" + this.options.propertyName); 
    } 
}; 

小提琴:http://jsfiddle.net/hieuh25/XXw5h/8/