[英]how to create jquery function using onstart and oncomplete
I'm trying to create my own jquery function, I know how to add options but don't know how to add 'onStart' or 'onComplete' functionality. 我正在尝试创建自己的jquery函数,我知道如何添加选项但不知道如何添加'onStart'或'onComplete'功能。
this is what I know so far: 这是我目前所知道的:
jQuery.somefunctionname = function (options) {
var settings = {},
defaults = {
'someoption': 'somevalue',
'someoption2': 'somevalue2',
'someoption3': 'somevalue3'
}
settings = $.extend({}, defaults, options);
//do something functional
alert("hey i'm a function");
}
But If I want the user to be able to add their own code in before (onStart) and after (onComplete) my function, what should I code? 但是如果我希望用户能够在我的函数之前(onStart)和之后(onComplete)添加自己的代码,我该怎么编码?
User should be able to write like this: 用户应该能够这样写:
$.somefunctionname({
'someoption' : 'a',
'someoption2' : 'b',
'someoption3' : 'c',
'onStart' : function() {
//whatever user want when my function started
},
'onComplete' : function() {
//whatever user want when my function ended
} });
thx ;) 谢谢 ;)
Within your function, do something like this: 在你的函数中,做这样的事情:
jQuery.somefunctionname = function (options) {
if (typeof options.onStart === "function")
options.onStart.call(this);
// other function code here
if (typeof options.onComplete === "function")
options.onComplete();
// OR
options.onComplete.call(this);
// OR
options.onComplete.apply(this, argsArrayIfDesired);
// etc.
};
That is, if the property is defined in options
and actually is a function then call it at the appropriate point. 也就是说,如果属性是在
options
定义的并且实际上是一个函数,那么在适当的位置调用它。 Specify a setting for this
using .call()
or .apply()
if desired, and include any parameters. 指定的设定
this
使用.call()
或.apply()
如果需要的话,并且包括任何参数。 Integrate with your settings
object or not as desired. 是否根据需要与您的
settings
对象集成。
Simply have a default value for those settings of jQuery.noop
, and then you can know that it is safe to call the value of that setting as a function, using apply()
or similar. 只需拥有
jQuery.noop
那些设置的默认值,然后您就可以知道使用apply()
或类似方法将该设置的值作为函数调用是安全的。
eg 例如
jQuery.somefunctionname = function (options) {
var settings = {},
defaults = {
'someoption': 'somevalue',
'someoption2': 'somevalue2',
'someoption3': 'somevalue3',
'onStart': jQuery.noop,
'onComplete': jQuery.noop
}
settings = $.extend({}, defaults, options);
settings.onStart.apply(this);
//do something functional
alert("hey i'm a function");
settings.onComplete.apply(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.