我想创建一个同时具有方法和回调的 jQuery 插件,方法可以工作,但我无法让回调工作,回调的范围让我感到困惑,
(function($)
{
var methods = {
create: function(options) {
var defaults = {
width: 320,
height: 240,
background: '#000',
onstop: function(){}
};
var options = $.extend(defaults, options);
return $(this).each(function(i) {
console.log('create');
});
},
stop: function(options) {
var defaults = {
onstop: function(){}
};
var options = $.extend(defaults, options);
return $(this).each(function(i) {
console.log('stop');
options.onstop.call();
});
}
};
$.fn.myplugin = function(option) {
if (methods[option]) {
return methods[option].apply( this, Array.prototype.slice.call(arguments, 1));
} else if (typeof option === 'object' || ! option) {
return methods.create.apply(this, arguments);
} else {
$.error('Method ' + option + ' does not exist in jQuery.plugin');
}
};
})(jQuery);
所以在<script>
:
$(document).ready(function(){
$('#start').click( function(){
$('#myvideo').myplugin('create', { onstop: function(){ console.log('on stop'); } });
});
$('#stop').click( function(){
$('#myvideo').myplugin('stop');
});
});
基本上,我似乎想让 onstop: function(){} 对插件全局化
/* ======== 更新代码(见注释) ======== */
(function($)
{
var callbacks = {
onready: $.Callbacks("once memory unique").add(function() {
//console.log('onready');
}),
ondeny: $.Callbacks("unique").add(function() {
//console.log('ondeny');
}),
onerror: $.Callbacks("unique").add(function() {
//console.log('onerror');
}),
onstop: $.Callbacks("unique").add(function() {
//console.log('onstop');
})
};
var methods = {
construct: function(){
},
create: function(options) {
var defaults = {
width: 320,
height: 240,
background: '#000',
onready: function(){},
onstop: function(){}
};
var options = $.extend(defaults, options);
return this.each(function(i, elements) {
for (var prop in options) {
if (prop in callbacks) {
callbacks[prop].add(options.prop);
}
}
callbacks.onready.fire();
});
},
stop: function() {
return this.each(function(i, elements) {
callbacks.onstop.fire();
});
}
};
$.fn.myplugin = function(option) {
if (methods[option]) {
return methods[option].apply( this, Array.prototype.slice.call(arguments, 1));
} else if (typeof option === 'object' || ! option) {
return methods.construct.apply(this, arguments);
} else {
$.error('Method ' + option + ' does not exist in jQuery.plugin');
}
};
})(jQuery);