Micor
Micor

Reputation: 1542

Re-using jQuery widgets

I am looking for a most efficient way to re-use widgets with different selectors... For example if I have:

$("#selector1").datepicker({
beforeShow: function(var1,var2) {
// do stuff
},
onClose: function(var1,var2) {
// do stuff
},
onSelect: function(var1,var2) {
// do stuff
}
})

And later I am looking to assign this same widget with same functions inside to other selectors which are not known at load time. Since its not about choosing a better selector and I want to avoid:

$("#new-selector2").datepicker({
beforeShow: function(var1,var2) {
// do stuff
},
onClose: function(var1,var2) {
// do stuff
},
onSelect: function(var1,var2) {
// do stuff
}
})

$("#new-selector3").datepicker({
beforeShow: function(var1,var2) {
// do stuff
},
onClose: function(var1,var2) {
// do stuff
},
onSelect: function(var1,var2) {
// do stuff
}
})

What would be the best way of doing something like:

var reusableDatepicker = datepicker({
beforeShow: function(var1,var2) {
// do stuff
},
onClose: function(var1,var2) {
// do stuff
},
onSelect: function(var1,var2) {
// do stuff
}
})

$("#selector1").attach(reusableDatepicker);
$("#new-selector2").attach(reusableDatepicker);
$("#new-selector3").attach(reusableDatepicker);

I know it has to be obvious to all jQuery devs out there, so obvious I cannot find it in docs :) Thank you!

Upvotes: 1

Views: 273

Answers (1)

Kobi
Kobi

Reputation: 138147

You can do exactly what you want by writing a plugin. However, a simple function will do here (in fact, this is the standard solution to code duplication):

function setDatepicker(selector){
    $(selector).datepicker({/* ... */});
}

setDatepicker("#selector1");
setDatepicker("#new-selector2");

Upvotes: 2

Related Questions