bootbox.js is a tiny and handy JavaScript library which allows one to create dialog boxes using Twitter’s Bootstrap modals programmaticallly.
Basic Example:
Recently there is a requirement in my project which requires prompting user with few questions and based on user’s response process further stuff.
My first choice was to use bootbox.js’s prompt function and I went with it.
But then after some time I started to feel like “Oops! I selected wrong library here.”. I don’t know how to call another bootbox.js
prompt in the callback of first one without any redundancy.
Moreover, I need to store the result of each prompt’s response for later processing purpose.
Then, my team lead suggested me to use Underscore’s partial function and gave me pseudo code.
Underscore’s partial function basically defines a function named _.partial
which accepts as a parameter a function and arbitrarily no. of arguments. The return value of _.partial
is a new function that when called will pass both its own parameters and the initially provided arguments to the original function.
Basic Example of _.partial
:
We can then call the increment function like this:
For the add
function in the above example, the parameter a
is fixed to
the value 1
. The first argument that’s passed to increment
will be passed to add
as the b
parameter.
The same technique I used in the implementation of invoking multiple bootbox.js prompts on successive prompt’s callback.
Implementation:
Here in showSurvey
, I am fixing first argument of callback
which refer to surveyCallback
passed from showSurvey
(line no. 53).
The second argument i.e. survey_response
of surveyCallback
(or callback
in showSurvey
)
will refer to bootbox.js prompt’s result(or user’s response).
Rest logic is simple. In surveyCallback
I am setting survey’s response in some variable
survey_answers
here and then fetching next first survey and repeating same iteration.