我正在使用以下代码作为我正在为一个项目开发的插件的基础 - 它来自 Smashing Magazine 上的一篇文章,位于此处,标题为“轻量级开始”:
http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
到目前为止,它对我的目的一直运行良好,但本文的其余部分偏离了主题,并讨论了我认为我需要 jQuery UI 库的 jQuery UI 小部件,但我真的不想使用这些小部件。
/*!
* jQuery lightweight plugin boilerplate
* Original author: @ajpiano
* Further changes, comments: @addyosmani
* Licensed under the MIT license
*/
// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;(function ( $, window, document, undefined ) {
// undefined is used here as the undefined global
// variable in ECMAScript 3 and is mutable (i.e. it can
// be changed by someone else). undefined isn't really
// being passed in so we can ensure that its value is
// truly undefined. In ES5, undefined can no longer be
// modified.
// window and document are passed through as local
// variables rather than as globals, because this (slightly)
// quickens the resolution process and can be more
// efficiently minified (especially when both are
// regularly referenced in your plugin).
// Create the defaults once
var pluginName = 'defaultPluginName',
defaults = {
propertyName: "value"
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
// Place initialization logic here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.options
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );
我现在需要为此添加一个方法,但我对如何做到这一点一无所知。
该方法需要以这样一种方式工作,即插件在页面上创建的实例可以通过控制台调用具有值的方法动态更改属性(最终这将通过其他进程发生,但控制台是现在很好)。
我将如何修改上面的代码以允许这样做?还是我在叫错树?
任何帮助将不胜感激,复杂的 JavaScript 有时会让我在黑暗中迷失方向,但我喜欢尽可能地尝试“最佳实践”。