在JQuery扩展函数中,如何访问实例选项?
问题描述:
我有功能的JQuery的扩展,我不知道如何访问实例的选项:在JQuery扩展函数中,如何访问实例选项?
(function ($) {
$.fn.MyExtension= function (methodOrOptions) {
if (methods[methodOrOptions]) {
return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
// Default to "init"
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + methodOrOptions + ' does not exist on jQuery.MyExtension');
}
};
var methods = {
init: function (options) {
var defaults = {
testOption: "test"
};
options = $.extend(defaults, options);
return this.each(function() {
// Code logic goes here
}
MyFunction: function() {
var optionVal = options.testOption;
}
};
})(jQuery);
所以这个代码抛出一个错误,当我打电话MyFunction的,因为它不知道什么是“选择”是。
答
将其存储在元素的数据对象上。 http://jsfiddle.net/U7QT5/
(function ($) {
$.fn.MyExtension = function (methodOrOptions) {
if (methods[methodOrOptions]) {
return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
// Default to "init"
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + methodOrOptions + ' does not exist on jQuery.MyExtension');
}
};
var methods = {
init: function (options) {
var defaults = {
testOption: "test"
};
return this.each(function() {
var $this = $(this);
$this.data("MyExtension",$.extend(defaults, options));
// Code logic goes here
});
},
MyFunction: function() {
var optionVal = this.data("MyExtension").testOption;
console.log(optionVal);
}
};
})(jQuery);
$("body").MyExtension({testOption: "foobar!"}).MyExtension("MyFunction");
答
所以,这只是一个简单的范围界定问题,我相信。你有对象选项被传递到init
,但它是本地的功能。您需要将其放在对象上,以便您的其他功能MyFunction
具有适用范围。
var methods = {
init: function (options) {
var defaults = {
testOption: "test"
};
this.currentOptions = $.extend(defaults, options);
return this.each(function() {
// Code logic goes here
}
MyFunction: function() {
var optionVal = this.currentOptions.testOption;
}
};