我有一个简单的(轻量级)div滑块,我之前写过,因为我在各种不同的项目中使用它 - 现在是将它包装到自己的插件中的时候了(冒着它不是这样的风险)轻量级了!)。
我一直在阅读,并且从http://docs.jquery.com/Plugins/Authoring复制,因为这是弹出我的插件樱桃,它有意义(大多数情况下),但有些东西在逃避我。这是我的插件代码:
(function( $ ) {
//List of callable methods
var methods = {
init : function(options) {
var settings = $.extend({
optionOne : 'aaa',
optionTwo : 'bbb',
optionThree : 'ccc',
optionFour : 'ddd'
}, options);
},
error : function(message) {
alert(message);
},
showSettings : function() {
//This bit... how to show whats in 'settings' defined in init?
}
}
$.fn.ccSlider = function( method ) {
//Calling methods
if (methods[method]) {
//If plugin is called with a recognised method, run that.
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if (typeof method === 'object' || !method) {
//if plugin is called without a method, run the init() function
return methods.init.apply( this, arguments );
} else {
//Run the error() function to catch all else.
return methods.error("ccSlider: Method '"+method+"' does not exist!");
}
};
})( jQuery );
这里的一切都按预期工作,但我不能继续编写我需要的方法,但仅仅因为我无法弄清楚如何在init()方法之外访问'settings'的内容。
我使用'showSettings'作为测试...我怎么写一个showSettings方法弹出并告诉我指定设置的值(比如说,optionTwo)是什么?
答案 0 :(得分:1)
您的架构正确,但方法和设置应该是您的插件的全局。
(function( $ ) {
var defaults = {
optionOne : 'aaa',
optionTwo : 'bbb',
optionThree : 'ccc',
optionFour : 'ddd'
} //if there are any
var settings = {}; //you can reach the settings from any where in your plugin now
//List of callable methods
var methods = {
init : function(options) {
//initialize the settings in your init function and you are good to go
settings = $.extend({},defaults,options);
},
error : function(message) {
alert(message);
},
showSettings : function() {
//This bit... how to show whats in 'settings' defined in init?
}
}
//your plugin code here like in your post but now you can use the settings variable we defined in your plugin
});