1

I would like the ability to add a custom function to an existing jquery class, similar to an extension method in C# (specifically datepicker).

I am able to get a static version of this working by declaring the below:

// declaration
$.ui.datepicker.hello = function () {
    alert('heya');
};

// caller
$.ui.datepicker.hello();

However as I am actually concerned with the specific instance of datepicker, I would much rathar be able to declare a function so I could do something like the below:

$("#date").datepicker.hello();
// Or
$("#date").datepicker("hello")

I have tried various methods including using jQuery.fn.extend() and the answers in add custom method to jquery ui dialog, but I get console errors stating "Object doesn't support this action" coming from jquery-ui.min.js when I attempt the accepted solution.

$.widget("ui.datepicker", $.ui.datepicker,{
    hello: function () {
        alert('yes');
    }
});

Is what I am trying to do even possible? Or is it just my execution that is lacking?

IanSoc
  • 238
  • 1
  • 3
  • 14
  • Your second snippet is indicating that you want to overwrite the existing `jQuery.fn.datepicker` with your own mutated version of it that would also accept in an argument value of 'hello' – Taplar Mar 21 '19 at 18:14
  • @Taplar I was attempting to copy how the built in datepicker methods are being called (e.g. $("#date").datepicker("getDate"); I suppose the main thing is that I wish to call a custom method on a specific instance, regardless of the format of it – IanSoc Mar 21 '19 at 18:19
  • @IanSoc after some research, `$.ui.datepicker` is not like the other widgets. It'll take some time to reseach how best to use this since making a mutation results in `TypeError: base is not a constructor`. If you look at `$.ui.datepicker` you see it has one index: `version` instead of what is expected. – Twisty Mar 22 '19 at 00:04
  • https://stackoverflow.com/questions/7733904/how-can-i-extend-jqueryui-datepicker-to-accept-an-additional-argument says: *You cannot extend because the datepicker does not use the widget factory and thus you can't use it to extend it but you can override the methods and can inject your code.* – Twisty Mar 22 '19 at 00:39
  • @Twisty interesting.... I had seen that question but I had missed the answer that you have quoted. I'll take a closer look at the answer and see if I figure something out. Thanks – IanSoc Mar 22 '19 at 08:55

0 Answers0