我想創建一個具有兩種方法,並回調一個jQuery插件,方法工作,但我不能讓工作的回調,回調的範圍混淆了我,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($)
{
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);
回調應該由插件的用戶設置,不是嗎? – Bergi
我想讓他們作爲選項訪問 – user780756