我正在开发一个 jQuery 插件,但我在设计模式方面遇到了一些问题,它结合了 jQuery 的 best practices 中的默认值和选项、数据和命名空间技术。 .这是我的代码的抽象版本:
(function($) {
var defaults = {
key1: 'value1',
key2: 'value2'
};
var settings = {};
var methods = {
init: function() {
return this.each(function() {
var $this = $(this), data = $this.data('pluginname');
console.log('init called');
// If the plugin hasn't been initialized yet
if (!data) {
//Do more setup stuff here
$this.data('pluginname', {
key3: 'value3',
key4: 'value4'
});
}
//test for settings and data
console.log(settings);
console.log(data);
});
},
methodname: function() {
return this.each(function() {
var $this = $(this), data = $this.data('pluginname');
console.log('methodname called');
//test for settings and data
console.log(settings);
console.log(data);
});
}
};
$.fn.pluginname = function(method, options) {
settings = $.extend({}, defaults, options);
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.pluginname' );
}
};
$(document).ready(function() {
$('body').pluginname();
$('body').pluginname('methodname', {key1: 'overriding default value for key 1'});
});
})(jQuery);
如果您使用最新版本的 jQuery 运行该代码,您将看到我同时调用了 init
和 methodname
函数并记录了 settings
和 data
对象。在 methodname
调用中,我可以访问 settings
和 data
,但在 init
调用本身中,data
对象返回未定义。如果我在第 21 行的脚本中设置断点,我可以在控制台中使用 $this.data('pluginname')
回调 data
对象。有人看到我在这里做错了吗?我应该能够在 init 函数中编写 data.key3
,对吗?
最佳答案
在您的 init
方法中,在 .each
循环的最开始,您将存储在当前迭代元素中的对象分配给您的 data
变量。如果指定键没有可用数据,则 data
未定义。
然后您测试 data
的真实性,如果它的计算结果为 false,您将继续并将数据对象分配给当前元素。
稍后,您调用 console.log(data);
,它会为您提供 undefined
。这是预料之中的,因为 data
最初被分配了 undefined
- 这就是它仍然引用的内容。修复:
// if undefined
if (!data) {
//Do more setup stuff here
$this.data('pluginname', {
key3: 'value3',
key4: 'value4'
});
data = $this.data('pluginname');
}
关于javascript - 具有数据持久性的 jQuery 插件模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7150239/