jQuery widget factory

在使用jQuery框架的时候,由于项目的特殊需求,常用的方法不能满足业务的时候就必须扩展方法实现需求,大家都知道常用的扩展方法,在javaeye上也有大量的文章说明在这里就不在重复了点击查看:[url]http://www.iteye.com/topic/545971[/url]。

在此处主要是记录下另外的一种扩展方式:直接上代码

$.widget('namespace.pluginName', {
_init: function() {
// stuff that is called on initialization of the plugin
//this.options a combination of the defualt options and the ones passed in during the plugin initialization
if (this.options.foo) {
//this.element is the element that the plugin was called on
this.element.fadeOut();
}
},
_privatemethod: function() {
//private internal function
//private functions should be named with a leading underscore
//will only be able to be called from inside the plugin
},
publicmethod: function() {
//this is a public fuction that can be called outside of the plugin
//calling the private method from inside the public method
this._privatemethod();
},
value: function() {
//this is a public function that is defined as a getter
//meaning it returns a value not a jquery object
return this.options.foo;
},
destory: function() {
$.widget.prototype.apply(this, arguments); // default destroy
// this is where you would want to undo anything you do on init to reset the page to before the plugin was initialized.
}

}));

$.extend($.namespace.pluginName, {
getter: 'value',
defaults: {
option1: 'bar',
foo: true
}
});

使用方法;在dom初始化插件为jquery对象后便可以调用对象上方法。
$('#myelement').pluginName();
$('#myelement').pluginName('publicmethod');


与前面介绍的扩展方式还是有些区别的,特点是并没有给所有的dom对象上扩展方法,而是在使用该方法的dom对象才回觉有插件中扩展方法。也就是说由用户指定的作用域中的dom元素才回绑定该扩展方法。jquery ui的大部分控件是基于$.Widget基类实现,这样通过不同的作用域也解决了函数命名冲突问题。

参考jQuery官网的解释:
[url]http://wifeng.cn/?p=150[/url]
[url]http://docs.jquery.com/UI_Developer_Guide#The_widget_factory[/url]
[url]http://blog.petersendidit.com/post/stateful-jquery-plugins-with-jquery-uis-widget-factory/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值