Last active
August 12, 2024 13:03
-
-
Save tomieric/9703999 to your computer and use it in GitHub Desktop.
jQuery插件模板
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jQuery Plugin Boilerplate | |
// A boilerplate for jumpstarting jQuery plugins development | |
// version 1.1, May 14th, 2011 | |
// by Stefan Gabos | |
// 中文 by tomieric | |
// 定义好插件名字,将以插件形式调用 | |
(function($) { | |
// 开始上手 | |
$.pluginName = function(element, options) { | |
// 插件默认配置 | |
// 私有属性只有被插件内部使用 | |
var defaults = { | |
foo: 'bar', | |
// 若插件作为事件驱动要提供可用的回调函数 | |
// 回调事件将在指定事件执行前或后调用 | |
// 插件应提供更多可配置参数 | |
onFoo: function() {} | |
} | |
// 避免变量名冲突, 为当前变量实例对象定义别名 | |
var plugin = this; | |
// 将合并默认配置与用户配置参数 | |
// 插件内部通过settings.属性访问,在外部可通过插件绑定元素的element.data('pluginName').settings.属性配置。 | |
plugin.settings = {} | |
var $element = $(element), // jQuery对象 | |
element = element; // Dom对象 | |
// 初始化化函数,构造函数实例化会调用init函数 | |
plugin.init = function() { | |
// 插件最终配置文件 | |
plugin.settings = $.extend({}, defaults, options); | |
// code goes here | |
} | |
// 公共函数 | |
// 内部通过plugin.methodName(arg1, arg2, ... argn)访问 | |
// 外部通过element.data('pluginName').publicMethod(arg1, arg2, ... argn)调用 | |
// foo_public_method只是示范,可以自己定义且定义多个 | |
plugin.foo_public_method = function() { | |
// code goes here | |
} | |
// 私有方法 | |
// 只能在插件内部使用 | |
// foo_private_method只是示范,可以自己定义且定义多个 | |
var foo_private_method = function() { | |
// code goes here | |
} | |
// 在实例化时初始化插件 | |
plugin.init(); | |
} | |
// 为jQuery.fn对象添加插件 | |
$.fn.pluginName = function(options) { | |
// 遍历选择器绑定插件 | |
return this.each(function() { | |
// 判断对象是否绑定插件 | |
if (undefined == $(this).data('pluginName')) { | |
// 创建一个实例化对象并传入配置参数 | |
var plugin = new $.pluginName(this, options); | |
// 用data存储实例化对象 | |
// 通过element.data('pluginName').publicMethod(arg1, arg2, ... argn) 或element.data('pluginName').settings.propertyName使用对象和其公开访问 | |
$(this).data('pluginName', plugin); | |
} | |
}); | |
} | |
})(jQuery); | |
/** 用法 **/ | |
$(document).ready(function() { | |
// 元素绑定插件 | |
$('#element').pluginName({'foo': 'bar'}); | |
// 调用公共方法 | |
$('#element').data('pluginName').foo_public_method(); | |
// 获取插架属性值 | |
$('#element').data('pluginName').settings.foo; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment