我正在尝试构建一个 Javascript 插件。它将是一个 slider /轮播,能够为每张幻灯片添加选项和操作。我知道周围已经有类似的插件,但首先我想在构建插件方面进行一些练习,然后我认为如果我需要它,按照我想要的方式扩展它可能会更容易。
这是我第一次尝试构建 Javascript 插件,在阅读了不同的设计模式后,我认为这可以满足我的需求:http://markdalgleish.com/2011/05/creating-highly-configurable-jquery-plugins/
所以,我的 html 会是这样的:
<div class="container">
<div class="item" data-step-in="stepin" data-step-out="stepout">item</div>
<div class="item" data-step-in="stepin2" data-step-out="stepout2">item</div>
<div class="item" data-step-in="stepin3" data-step-out="stepout3">item</div>
</div>
理想情况下,我想在容器元素上调用插件并让它为每个元素设置所有选项:
$('.container').slider();
基本的插件结构是:
(function(window, $) {
var Plugin = function(elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.items = {};
};
Plugin.prototype = {
defaults: {
message: 'Hello world!',
itemsClass: '.item'
},
init: function() {
this.config = $.extend({}, this.defaults, this.options);
$(this.config.itemsClass).each(function(i, obj) {
console.log(i, obj);
this.items[i][item] = obj; <--- problem!
});
return this;
},
};
Plugin.defaults = Plugin.prototype.defaults;
$.fn.slider = function(options) {
return this.each(function() {
new Plugin(this, options).init();
});
};
window.Plugin = Plugin;
})(window, jQuery);
在 init
函数中,我想迭代这些项目,并将它们与所有选项一起存储在一个全局对象中。这就是我失败的地方。在 each
循环内,this
指的是迭代的单个项目。那么,从这里开始,我该如何在构造函数中引用 this.items
呢?这里最好的方法是什么?此用途的模式是否错误?
最佳答案
将您想要的this
存储在变量中并从那里调用:
init: function() {
var that = this;
that.config = $.extend({}, that.defaults, that.options);
$(that.config.itemsClass).each(function(i, obj) {
console.log(i, obj);
that.items[i][item] = obj; <--- problem!
});
return that;
},
尽管 this
会根据范围而改变,that
将保持与您在函数开始时设置的内容相同
关于高度可定制插件模式中的 Javascript 范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35669958/