Re-using jQuery widgets

Posted by Micor on Stack Overflow See other posts from Stack Overflow or by Micor
Published on 2010-04-10T07:50:44Z Indexed on 2010/04/10 7:53 UTC
Read the original article Hit count: 364

Filed under:
|

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!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-ui