I am trying to create my first own jQuery function to re-order some rows in a table.
The function works fairly well, I am just unsure how to fire the callback functions which i should be able to set in the settings object. Also is this the way to make a jQuery function? The code can be seen in action here: http://jsfiddle.net/fcHQh/
The function is:
(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 );
asked Feb 14, 2012 at 13:24
janhartmann
15k17 gold badges89 silver badges142 bronze badges
1 Answer 1
I suggest you have a defaults object, and merge that with your options:
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
});
},
// ...
answered Feb 14, 2012 at 13:30
Linus Thiel
39.3k9 gold badges112 silver badges104 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Linus Thiel
The gist is that you don't want to overwrite your defaults, and possibly not the options passed, but you want to create a copy where you have your defaults, and if present, your options. $.extend achieves that. See api.jquery.com/jQuery.extend
Linus Thiel
And here is a good primer on writing jQuery plugins: docs.jquery.com/Plugins/Authoring
Linus Thiel
I wasn't sure what you meant by // THIS SHOULD ONLY BE FIRED IF CALLBACK IS DEFINED? - I figured you wanted to control that with some setting?
janhartmann
Yeah, I figured it out. I was a comment for my head. I have it figured out now and it works - thank you!
lang-js