我正在尝试创建我自己的第一个jQuery函数来重新排序表中的某些行。
该函数工作得很好,我只是不确定如何触发我应该能够在设置对象中设置的回调函数。这也是制作jQuery函数的方法吗?代码可以在这里看到:http://jsfiddle.net/fcHQh/
功能是:
(function( $ ){
$.fn.reorder = function(options) {
var settings = {
'up': '.up',
'down': '.down',
'timeout': 1000,
'url': '',
'success': null,
'error': null
};
var methods = {
init : function(element) {
$(settings.up + ',' + settings.down).on('click', function (event) {
event.preventDefault();
var row = $(this).parents('tr:first');
if ($(this).is(settings.up)) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
tools.delay(function() { methods.sort(element) }, settings.timeout);
});
},
sort : function(element) {
$(element).find('tr').find('input:hidden').each(function () {
element.priorities.push($(this).val());
});
if (settings.url) {
methods.callback(element);
}
},
callback : function(element) {
// THIS SHOULD ONLY BE FIRED IF CALLBACK IS DEFINED?
$.ajax({
type: 'GET',
url: settings.url,
data: { priorities: element.priorities.join(',') },
success: function() {
// FIRE THE 'settings.success' if its set
},
error: function() {
// FIRE THE 'settings.error' if its set
}
});
}
};
var tools = {
delay : (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})()
}
return this.each(function() {
if (options) $.extend(settings, options);
this.priorities = [];
methods.init(this);
});
};
})( jQuery );
答案 0 :(得分:2)
我建议您有一个默认对象,并将其与您的选项合并:
var defaults = {
up: '.up',
down: '.down',
timeout: 1000,
url: '',
success: function() {},
error: function() {}
};
var settings = $.extend({}, defaults, options);
// ...
callback: function() {
$.ajax({
success: settings.success,
error: settings.error
});
},
// ...