我有一个带函数的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时,此代码会抛出错误,因为它不知道“选项”是什么。
答案 0 :(得分:1)
将其存储在元素的数据对象上。 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");
答案 1 :(得分:0)
所以,我相信这只是一个简单的范围界定问题。您将对象选项传递到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;
}
};