5

I'm using the select2 jQuery plugin (V4) and from what I can see they don't have an onInitialized event; but I need to run some code after it has been initialized.

By Initialized I mean that it has completed and that all elements associated to it are now ready.

I seen this question, but none of the answers seem to address the issue of continually checking until it becomes available; like what if it's not there the first time you check, then the code you needed to run wouldn't run.

I thought of using setInterval with something like the above but wasn't sure if there was a better way?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Brett
  • 19,449
  • 54
  • 157
  • 290
  • Just checking what you mean by "initialised": Do you want to check that Select2 is download and registered as a jQuery function before calling it with `$('select').select2();`? Or do you want to check that `$('select').select2();` is complete before doing something else? – Lesley May 24 '16 at 15:46
  • @Lesley Sorry, I mean *completed*. I have updated my question. – Brett May 24 '16 at 15:53
  • The question you linked to is about checking that a plugin is downloaded and registered as a jQuery function. If you want to do something after the call to `select2()` is complete, my first thought was: Why not just put the code for the stuff you want to do post-init after the call to Select2? `$('#my-select').select2(); console.log('This should happen after select2() is done');` – Lesley May 26 '16 at 14:36
  • @Lesley Whilst you are giving it the command *after* the call to `select2` since JavaScript is synchronous and not asynchronous by default then wouldn't this mean that `select2` may not necessarily be finished executing when you run code after it? – Brett May 26 '16 at 14:55
  • 1
    It depends what Select2 is doing under the hood... I suppose it's possible it says `return` before it's really finished and then does further work due to some async callback or whatever. Do you have a situation which is indicating this is the case? – Lesley May 26 '16 at 15:27
  • @Lesley Not really, just wanted to be thorough. – Brett May 26 '16 at 16:50

2 Answers2

0

The only way you can go async it's when you fetching remote data, so you can inject you callback in that ajax.

If you have several ajax calls use deferred:

var deffered1 = $.Deferred();

In your ajax calls after success and error use the following code to resolve those calls.

complete:function(){
    deffered1.resolve()
}

And to subscribe for events:

$.when(deffered1, deffered2).done(function() {
    // your initialized actions
})
Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
faster
  • 151
  • 5
0

If you have more than 1 select elements on your page which needs to be converted to select2 dropdown then you can use the following: Multi Select version

if you have just a single select on the page, you can go with the following: Single Select option:

Hope it helps.

Aalok Mishra
  • 176
  • 1
  • 11