forked from DivadNojnarg/outstanding-shiny-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shiny-input-system.Rmd
1356 lines (1069 loc) · 64.2 KB
/
shiny-input-system.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Understand and develop new Shiny inputs {#shiny-input-system}
Shiny __inputs__ are key elements of Shiny apps since they are a way for the end-user to __interact__ with the app. You may know `sliderInput()`, `numericInput()` and `checkboxInput()`, but sometimes you may need fancier elements like `knobInput()` from [shinyWidgets](https://github.com/dreamRs/shinyWidgets/blob/5566202a4b9a0899eaafa36da23f076454bc9622/R/input-knob.R#L69), as depicted in Figure \@ref(fig:fancy-inputs) or even more sophisticated inputs like the [shinyMobile](https://github.com/RinteRface/shinyMobile/blob/93eaffee6a8941376802ae867add36407531e19d/R/f7-inputs.R) `smartSelect()` (Figure \@ref(fig:fancy-inputs), right panel). Have you ever wondered what mechanisms are behind inputs? Have you ever dreamed of developing your own?
The goal of this section is to understand how Shiny inputs work and how to create new ones.
```{r fancy-inputs, echo=FALSE, fig.show = "hold", out.width = "50%", fig.align = "default", fig.cap='Custom shiny inputs. left: knobInput from shinyWidgets; right: smart select from shinyMobile.'}
knitr::include_graphics("images/survival-kit/jquery-knobs.png")
knitr::include_graphics("images/survival-kit/smart-select.png")
```
## Input bindings {#input-binding}
When we run our app, most of the time it works just fine. The question is, what is the magic behind? Upon initialization, Shiny runs several JavaScript functions, some of them being exposed to the programmer, through the __Shiny__ JS object, already mentioned in section \@ref(shiny-js-object). To illustrate what they do, let's run the app below:
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/dummy-app", view_code = FALSE), "r")
```
We then open the HTML inspector and run `Shiny.unbindAll(document)`; with document being the scope, that is where to search. Try to change the slider input. You will notice that nothing happens. Now let's type `Shiny.bindAll(document)` and update the slider value. Moving the slider successfully updates the plot. Magic, isn't it? This simply shows that when inputs are not bound, nothing happens so __binding__ inputs is necessary.
We consider another example with multiple inputs and two buttons to bind/unbind inputs, respectively. Start it, change some input values, have a look at the corresponding text output. Click on unbind all and try to change some inputs. What happens? Click on bind and change another input value. What do you observe?
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/bind-unbind"), "r")
```
Let's see below what is an __input binding__ and how it works.
### Input structure
In HTML, an input element is given by the `<input>` tag, as well as several attributes.
```{r, echo=FALSE, results='asis'}
html_code <- '<input id = "id" type = "text" class = "..." value = value>'
code_chunk_custom(html_code, "html")
```
- __id__ guarantees the input uniqueness and a way for Shiny to recover it in the `input$<id>` element.
- [type](https://www.w3schools.com/tags/att_input_type.asp) like `checkbox`, `button`,
`text` ...__type__ may also be a good target for the input binding find method, as explained below.
- __class__ may be required to find the element in the DOM. It is more convenient for
an input binding to target a class (and all associated elements) rather than an id, which corresponds to one element by definition. It is also used by CSS to apply styles.
- __value__ holds the input value.
### Binding Shiny inputs {#input-binding-steps}
An __input binding__ allows Shiny to identify each __instance__ of a given input and what you may do with this input. For instance, a slider input must update whenever the range is dragged or when the left and right arrows of the keyboard are pressed. It relies on a class defined in the `input_binding.js` [file](https://github.com/rstudio/shiny/blob/60db1e02b03d8e6fb146c9bb1bbfbce269231add/srcjs/input_binding.js).
Let's describe each method chronologically. For better convenience, the book side package contains step-by-step demonstrations which may be found [here](https://github.com/DivadNojnarg/OSUICode/blob/43911d32885e960d6f42c7bd7d92748109f29f00/R/inputs.R). Each example is called by the `customTextInputExample()`, which takes the input binding step as the only parameter. For instance, `customTextInputExample(1)` will invoke the first step, while `customTextInputExample(4)` will include all steps from 1 to 4.
#### Find the input
The first step is critical, which requires __locating__ the input in the __DOM__. On the R side, we define an input, with a specific attribute that will serve as a __receptor__ for the binding. For most of inputs, this may be handled by the __type__ attribute. In other cases, this may be the __class__, like for the `actionButton()`. On the JS side, we need a method able to identify this receptor. Moreover, two different types of inputs (for instance `radioButton()` and `selectInput()`) cannot have the same receptor for conflict reasons, whereas two instances of the same input type can. If your app contains 10 sliders, they all share the same input binding, and this is where the thing is powerful since they are all bound in one step. The receptor identifier is provided by the __find__ method of the `InputBinding` class. This method must be applied on a __scope__; that is, the `document`. `find` accepts any valid jQuery selector:
```{r, echo=FALSE, results='asis'}
js_code <- "find: function(scope) {
return $(scope).find('.input-text');
}"
code_chunk_custom(js_code, "js")
```
::: {.importantblock data-latex=""}
Don't forget the `return` statement. Omitting it would cause the binding step to fail, as well as all other downstream
steps.
:::
Figure \@ref(fig:shiny-find-inputs) summarizes this important step.
```{r shiny-find-inputs, echo=FALSE, fig.cap='How to find inputs.', out.width='100%'}
knitr::include_graphics("images/survival-kit/shiny-find-inputs.png")
```
Below, we are going to re-create `textInput()` binding, step by step. As `{shiny}` already provides bindings for the `textInput()`, we don't want them to recognize our new input. Therefore, we add a new `input-text` class and make our own input binding pointing to that specific class:
```{r}
customTextInput <- function (
inputId,
label,
value = "",
width = NULL,
placeholder = NULL,
binding_step
) {
# this external wrapper ensure to control the input width
div(
class = "form-group shiny-input-container",
style = if (!is.null(width)) {
paste0("width: ", validateCssUnit(width), ";")
},
# input label
shinyInputLabel(inputId, label),
# input element + JS dependencies
tagList(
customTextInputDeps(binding_step),
tags$input(
id = inputId,
type = "text",
class = "form-control input-text",
value = value,
placeholder = placeholder
)
)
)
}
```
The last part of the code contains a `tagList()` with two elements:
- The element input binding, `customTextInputDeps()`. `binding_step` allows us to review one step at a time, which is easier from a learning perspective.
- The input tag.
Below is an example of how we managed the dependency creation in the side package.
If we had multiple inputs, we would add more script to the dependency by passing a vector to the script parameter.
```{r, eval=FALSE}
customTextInputDeps <- function(binding_step) {
htmlDependency(
name = "customTextBindings",
version = "1.0.0",
src = c(file = system.file(
"input-system/input-bindings",
package = "OSUICode"
)),
script = paste0(
"customTextInputBinding_",
binding_step,
".js"
)
)
}
```
Figure \@ref(fig:text-input) shows the main elements of the `textInput()` widget. In the above code, `shinyInputLabel` is a Shiny internal function that creates the numeric input label, or in other words the text displayed next to it. The core input element is wrapped by `tags$input`.
```{r text-input, echo=FALSE, fig.cap='Shiny\'s textInput elements.', out.width='100%', fig.align='center'}
knitr::include_graphics("images/survival-kit/text-input.png")
```
We invite the reader to run the full working demonstration exposed below.
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/binding-find"), "r")
```
In short, this example consists of a simple text input and an output showing the current text input value:
```{r, eval=FALSE}
customTextInputExample <- function(binding_step) {
ui <- fluidPage(
customTextInput(
inputId = "caption",
label = "Caption",
value = "Data Summary",
binding_step = binding_step
),
textOutput("custom_text")
)
server <- function(input, output) {
output$custom_text <- renderText(input$caption)
}
shinyApp(ui, server)
}
```
We open the developer tools to inspect the `customTextInputBinding.js` script, put a breakpoints in the `find` method and reload the page. Upon reload, the JavaScript debugger opens, as shown Figure \@ref(fig:binding-find). Type `$(scope).find('.input-text')` in the console, and see what is displayed. This is the DOM element, which you may highlight when you hover over the JavaScript output.
Building input bindings like this significantly ease the debugging process, and you'll get more chances to be successful!
```{r binding-find, echo=FALSE, fig.cap='Find is the first method triggered.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-find.png")
```
Now, let's see why it is better to target elements by type or class. We run the below example.
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/binding-find-2"), "r")
```
This is a demonstration app containing two text inputs. Moreover, the binding is modified so that it looks for element having a specific id:
```{r, echo=FALSE, results='asis'}
js_code <- "find: function(scope) {
return $(scope).find('#mytextInput');
}"
code_chunk_custom(js_code, "js")
```
If you repeat the above debugging steps, `$(scope).find('.input-text')` only targets the
first text input, meaning that the second input will not be found and bound, as demonstrated in Figure \@ref(fig:binding-find-by-id).
```{r binding-find-by-id, echo=FALSE, fig.cap='Find by id is a rather bad idea.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-find-by-id.png")
```
As a side note, you'll also get an error in the binding (`Uncaught Not implemented`), indicating that the `getValue` method is not implemented yet. Fear not! We are going to add it very soon.
#### Initialize inputs
Upon initialization, Shiny calls the `initializeInputs` function that takes all input bindings and calls their __initialize__ method before binding all inputs. Note that once an input has been initialized, it has a `_shiny_initialized` tag to avoid initializing it twice. The `initialize` method is not always defined but some elements require to be explicitly initialized or activated. For instance the [Framework7](https://framework7.io) API, on top of which `{shinyMobile}` [@R-shinyMobile] is built, requires instantiating all elements. Below is an example for the [toggle](https://framework7.io/docs/toggle.html) input:
```{r, echo=FALSE, results='asis'}
js_code <- "// what is expected
let toggle = app.toggle.create({
el: '.toggle',
on: {
change: function () {
console.log('Toggle changed')
}
}
});"
code_chunk_custom(js_code, "js")
```
`el: '.toggle'` means that we are looking at the element(s) having the `toggle` class. `app.toggle.create` is internal to the Framework7 API. The corresponding `{shinyMobile}` input binding starts as follows:
```{r, echo=FALSE, results='asis'}
js_code <- "let f7ToggleBinding = new Shiny.InputBinding();
$.extend(f7ToggleBinding, {
initialize: function(el) {
app.toggle.create({el: el});
},
// other methods
});"
code_chunk_custom(js_code, "js")
```
Once initialized, we may use all specific methods provided by the API. [Framework7](https://framework7.io) is clearly a gold mine, as its API provides many possible options for many inputs/widgets. We provide more examples in Chapters \@ref(mobile-shinyMobile) and \@ref(mobile-widgets).
#### Get the value
The __getValue__ method returns the input value. The way to obtain the value is different for almost all inputs. For instance, the `textInput()` is pretty simple since the value is located in the `value` attribute. __el__ refers to the element holding the id attribute and recognized by the `find` method. Figure \@ref(fig:shiny-el) shows the result of a `console.log($(el));`.
```{r shiny-el, echo=FALSE, fig.cap='About the el element.', out.width='100%'}
knitr::include_graphics("images/survival-kit/shiny-el.png")
```
```{r, echo=FALSE, results='asis'}
js_code <- "getValue: function(el) {
console.log($(el));
return $(el).val();
}"
code_chunk_custom(js_code, "js")
```
To get the value, we apply the jQuery method `val` on the `$(el)` element and return the result.
::: {.importantblock data-latex=""}
Don't forget the `return` statement.
:::
Similarly as in the find section, we run the below example and open the developer tools to inspect the `customTextInputBinding_2.js` script.
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/binding-get"), "r")
```
We put breakpoints in the `getValue` method and reload the page. Upon reload, the JavaScript debugger opens starts in `find`. You may click on the next blue arrow to jump to the next breakpoint that is `getValue`, as shown Figure \@ref(fig:binding-getValue). Typing `$(el).val()` in the console shows the current
text value.
```{r binding-getValue, echo=FALSE, fig.cap='getValue returns the current input value.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-getValue.png")
```
Clicking on next again will exit the debugger. Interestingly, you'll notice that a text appears below the input, meaning that the `input$caption` element exists and is internally tracked by Shiny. Notice that when you try to change the text content, the output value does not update as we would normally expect. We are actually omitting a couple of methods that prevent the binding from being fully functional. We will introduce them in the following sections.
#### Set and update
__setValue__ is used to set the value of the current input. This method is necessary so that the input value may be __updated__. It has to be used in combination with __receiveMessage__, which is the JavaScript part of all the R __update<INPUT_NAME>Input__ functions, like `updateTextInput()`. We usually call the `setValue` method inside.
```{r, echo=FALSE, results='asis'}
js_code <- "// el is the DOM element.
// value represents the new value.
setValue: function(el, value) {
$(el).val(value);
}"
code_chunk_custom(js_code, "js")
```
Let's create a function to update our custom text input. Call it `updateCustomTextInput`. It requires at least three parameters:
- __inputId__ tells which input to update.
- __value__ is the new value. This will be taken by the `setValue ` JS method in the input binding.
- __session__ is the Shiny session object mentioned earlier in section \@ref(shiny-session). We will use the __sendInputMessage__ to send values from R to JavaScript. The `receiveMessage` method will apply `setValue` with the data received from R. The current session is recovered with `getDefaultReactiveDomain()`.
```{r}
updateCustomTextInput <- function(
inputId,
value = NULL,
session = getDefaultReactiveDomain()
) {
session$sendInputMessage(inputId, message = value)
}
```
We add `setValue` and `receiveMessage` to custom input binding.
Figure \@ref(fig:shiny-update-inputs) illustrates the main mechanisms.
```{r shiny-update-inputs, echo=FALSE, fig.cap='Events following a click on the update button. This figure demonstrates how R and JS communicate, through the websocket.', out.width='100%'}
knitr::include_graphics("images/survival-kit/shiny-update-inputs.png")
```
If we have to pass multiple elements to update, we would have to change the `updateCustomTextInput` function such as:
```{r}
updateCustomTextInput <- function(
inputId,
value = NULL,
placeholder = NULL,
session = getDefaultReactiveDomain()
) {
message <- dropNulls(
list(
value = value,
placeholder = placeholder
)
)
session$sendInputMessage(inputId, message)
}
```
`shiny:::dropNulls` is an internal function ensuring that the list does not contain `NULL` elements. We send a list from R, which is then serialized to a JSON object. In the `receiveMessage` method, properties like `value` may be accessed using the `.` notation. It is good practice to add a `data.hasOwnProperty` check to avoid running code
if the specified property does not exist:
```{r, echo=FALSE, results='asis'}
js_code <- "// data are received from R.
// It is a JS object.
receiveMessage: function(el, data) {
console.log(data);
if (data.hasOwnProperty('value')) {
this.setValue(el, data.value);
}
// other parameters to update...
}"
code_chunk_custom(js_code, "js")
```
::: {.noteblock data-latex=""}
__this__ refers to the custom text input binding class (which is an object), so that `this.setValue` allows calling the `setValue` method.
:::
Similarly to the previous sections, we run `updateCustomTextInputExample(3)` and open the developer tools to inspect the `customTextInputBinding_3.js` script.
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/binding-receive"), "r")
```
We put breakpoints in the `receiveMessage` and `setValue` methods and reload the page. Upon reload, the JavaScript debugger opens starts in `find`. You may click on the next blue arrow until you reach `receiveMessage`, as shown Figure \@ref(fig:binding-receive). Inspecting the `data` object, it contains only one property, namely the value. In practice, there may be more complex structure. As an exercise, you may change the `data.value` to whatever value you want.
```{r binding-receive, echo=FALSE, fig.cap='Receive a message from R.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-receive.png")
```
Clicking on the next arrow makes us jump in the next call that is `setValue`, where we can print the value to check whether it is correct. Running `$(el).val(value);` in the debugger console instantaneously update the DOM element with the new text, as shown in Figure \@ref(fig:binding-setValue).
```{r binding-setValue, echo=FALSE, fig.cap='Set the new value.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-setValue.png")
```
So far so good. We managed to update the text input value on the client. Yet, after clicking the button, the output value still does not change. We are going to fix this missing step in the next section.
#### Subscribe
__subscribe__ listens to __events__ defining Shiny to update the input value and make it available in the app. Some API like Bootstrap explicitly mention those events (like `hide.bs.tab`, `shown.bs.tab`, ...).
Going back to our custom text input, what event would make it change?
- After a key is released on the keyboard. We may listen to `keyup`.
- After copying and pasting any text in the input field or dictating text. The `input` event may be helpful.
We add those [events](https://javascript.info/events-change-input) to our binding using an __event listener__ seen in Chapter \@ref(survival-kit-javascript).
```{r, echo=FALSE, results='asis'}
js_code <- "$(el).on(
'keyup.customTextBinding input.customTextBinding',
function(event) {
callback(true);
});"
code_chunk_custom(js_code, "js")
```
::: {.noteblock data-latex=""}
Notice the event structure: `EVENT_NAME.BINDING_NAME`. It is best practice to follow this
convention.
:::
The __callback__ parameter ensures that the new value is captured by Shiny. Chapter \@ref(shiny-input-lifecycle) provides more details, but this is quite technical.
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/binding-subscribe"), "r")
```
We run the above example, open the HTML inspector, select the `customTextInputBinding_4.js` script and put a breakpoint in the `getValue`, as well as `subscribe` method. We enter a new text inside the input field, which triggers the debugger inside the `subscribe` call. Inspecting the event object, the type indicates the action, which is an input action and the target is the text input element itself, depicted in Figure \@ref(fig:binding-subscribe-1).
```{r binding-subscribe-1, echo=FALSE, fig.cap='Subscribe method after the text input manual update.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-subscribe-1.png")
```
We click on next and notice that we go back in the `getValue` method to get the new value.
You may check typing `$(el).val()` in the debugger console, like in Figure \@ref(fig:binding-subscribe-2). Clicking next again shows the updated output value.
```{r binding-subscribe-2, echo=FALSE, fig.cap='Subscribe is followed by a new getValue.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-subscribe-2.png")
```
Hooray! The output result is successfully changed when the input value is manually updated. However, it is not modified when we click on the update button. What did we miss? Looking back at the `receiveMessage` method, we changed the input value, but how does Shiny knows that this step was successful? To check that no event is raised, we put a `console.log(event);` in the `subscribe` method. Any action like removing the text content or adding new text triggers event, but clicking on the action button does not. Therefore, we must trigger an event and add it to the `subscribe` method. We may choose the `change` event, which triggers when an element is updated. Notice the parameter passed to callback. We discuss it in the next part!
```{r, echo=FALSE, results='asis'}
js_code <- "$(el).on('change.customTextBinding', function(event) {
callback(false);
});"
code_chunk_custom(js_code, "js")
```
Besides, in the `receiveMessage` we must trigger a `change` event to trigger the subscribe method:
```{r, echo=FALSE, results='asis'}
js_code <- "receiveMessage: function(el, data) {
if (data.hasOwnProperty('value')) {
this.setValue(el, data.value);
$(el).trigger('change');
}
}"
code_chunk_custom(js_code, "js")
```
Let's try again.
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/binding-subscribe-2"), "r")
```
We put a new break point in the second event listener, that is, the one for the change event. Clicking on the button only triggers the change event, as shown Figure \@ref(fig:binding-subscribe-3).
```{r binding-subscribe-3, echo=FALSE, fig.cap='Add multiple event listeners inside the subscribe method.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-subscribe-3.png")
```
::: {.warningblock data-latex=""}
... In some situations, we have to be careful with the __this__ element. Indeed, called in an event listener, `this` refers to the element that triggered the event and not to the input binding object. For instance, below is an example where we need to trigger the `getValue` method inside an event listener located in the `subscribe` method. If you call `this.getValue(el)`, you'll get an error. The trick consists of creating a variable, namely __self__, which takes `this` as value, outside the event listener. In that case, `self` refers to the binding itself, and it makes sense to call `self.getValue(el)`:
```{r, echo=FALSE, results='asis'}
js_code <- "subscribe: function(el, callback) {
self = this;
$(el).on('click.button', function(e) {
var currentVal = self.getValue(el);
$(el).val(currentVal + 1);
callback();
});
}"
code_chunk_custom(js_code, "js")
```
:::
Perfect? Not exactly.
#### Setting rate policies
It would be better to only change the input value once the keyboard is completely released for some time (and not each time a key is released). This is what we call __debouncing__, which allows a __delay__ before telling Shiny to read the new value, and it is achieved using the __getRatePolicy__ method. Additionally, we must also pass `true` to the `callback` in the subscribe method, in order to apply our specific rate policy ([debounce](https://davidwalsh.name/javascript-debounce-function), throttle). This is useful, for instance, when we don't want to flood the server with useless update requests. For example, when using a slider, we only want to send the value as soon as the range stops moving and not all intermediate values. Those elements are defined [here](https://github.com/rstudio/shiny/blob/60db1e02b03d8e6fb146c9bb1bbfbce269231add/srcjs/input_rate.js).
Run the below app and try to manually change the text input value by adding a couple of letters as fast as you can. What do you notice? We see the output value only updates when we release the keyboard.
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/binding-rate-policies"), "r")
```
You may adjust the delay according to your needs, but we caution to not set the delay too long as this becomes problematic too (unnecessary lags).
If you want to get an overview of all binding steps, you may try the following [slide](https://rinterface.com/shiny/talks/RPharma2020/?panelset1=r-code2#45) from the 2020 R in Pharma workshop.
#### Register an input binding
At the end of the input binding definition, we register it for Shiny.
```{r, echo=FALSE, results='asis'}
js_code <- "let myBinding = new Shiny.inputBinding();
$.extend(myBinding, {
// methods go here
});
Shiny.inputBindings.register(
myBinding,
'PACKAGE_NAME.BINDING_NAME'
);"
code_chunk_custom(js_code, "js")
```
Best practice is to name it following `PACKAGE_NAME.BINDING_NAME`, to avoid conflicts.
Although the Shiny [documentation](https://shiny.rstudio.com/articles/building-inputs.html) mentions a `Shiny.inputBindings.setPriority` method to handle conflicting bindings, if you respect the above convention, this case almost never happens.
As a side note, if you think that the binding name is useless, have a look at the `{shinytest}` internal structure.
Under the hood, it has a [file](https://github.com/rstudio/shinytest/blob/dea2ecc9f9d87f98fa109a6959b07d3e6e3ff4f3/R/shiny-mapping.R#L56), which maps all input elements:
```{r, eval=FALSE}
widget_names <- c(
"shiny.actionButtonInput" = "actionButton",
"shiny.checkboxInput" = "checkboxInput",
"shiny.checkboxGroupInput" = "checkboxGroupInput",
```
Guess what? Those names are the ones given during the input binding registration.
#### Other binding methods
There are a couple of methods not described above that are contained in the `InputBinding` class __prototype__. They were not described before since, most of the time, we don't need to change them and can rely on the defaults:
- __getId__ returns the object id (Figure \@ref(fig:binding-getId)). If you don't provide your own method, the binding falls back to the default one provided in the `InputBinding` class. This method is called after the `find` step. Chapter \@ref(shiny-input-lifecycle) provides more details.
- __getType__ required to handle custom data formats. It is called after `getId`. An entire section \@ref(custom-data-format) is dedicated to this.
```{r binding-getId, echo=FALSE, fig.cap='The binding getId method.', out.width='100%'}
knitr::include_graphics("images/survival-kit/binding-getId.png")
```
### Edit an input binding {#edit-input-binding}
In some cases, we would like to access the input binding and change its default behavior, even though not always recommended, since it will affect **all** related inputs. As bindings are contained in a registry, namely `Shiny.inputBindings`, one may seamlessly access and modify them. This is a five-step process:
1. Wait for the `shiny:connected` [event](https://shiny.rstudio.com/articles/js-events.html), so that the `Shiny` JS
object exists.
2. Unbind all inputs with `Shiny.unbindAll()`.
3. Access the binding registry, `Shiny.inputBindings`.
4. Extend the binding and edit its content with `$.extend(... {...})`
5. Apply the new changes with `Shiny.bindAll()`.
```{r, echo=FALSE, results='asis'}
js_code <- "$(function() {
$(document).on('shiny:connected', function(event) {
Shiny.unbindAll();
$.extend(Shiny
.inputBindings
.bindingNames['shiny.actionButtonInput']
.binding, {
// do whathever you want to edit existing methods
});
Shiny.bindAll();
});
});"
code_chunk_custom(js_code, "js")
```
### Update a binding from the client {#update-binding-client}
The interest of `receiveMessage` and `setValue` is to be able to update the input
from the server side, that is R, through the `session$sendInputMessage`. Yet,
this task might be done directly on the client, thereby lowering the load on the server.
We consider the following example: a Shiny app contains two action buttons; clicking on the first one
increases the value of the second by 10. This won't be possible with the classic approach since a button click
only increases its value by 1. How do we proceed?
1. We first set an event listener on the first button.
2. We target the second button and get the input binding with `$obj.data('shiny-input-binding')`.
3. We recover the current value.
4. We call the `setValue` method, adding 10 to the current value.
5. Importantly, to let Shiny update the value on the R side, we must trigger an event that will be detected in the `subscribe` method. The action button only has one event listener, but other may be added. Don't forget that triggering a `click` event would also increment the button value by 1! In the following, we have to customize the `subscribe` method to work around:
```{r, echo=FALSE, results='asis'}
js_code <- "$(function() {
// each time we click on #test (a button)
$('#button1').on('click', function() {
let $obj = $('#button2');
let inputBinding = $obj.data('shiny-input-binding');
let val = $obj.data('val') || 0;
inputBinding.setValue($obj, val + 10);
$obj.trigger('event');
});
});"
code_chunk_custom(js_code, "js")
```
If you click on the second button, the value increments only by 1 and the plot will be only visible after 10 clicks, while only 1 click is necessary on the first button. The reset button resets the second action button value to 0.
```{r, echo=FALSE, results='asis'}
js_code <- "$('#reset').on('click', function() {
let $obj = $('#button2');
let inputBinding = $obj.data('shiny-input-binding');
inputBinding.reset($obj);
$obj.trigger('change');
});"
code_chunk_custom(js_code, "js")
```
It implements the feature discussed in the previous part, where we extend the button binding to add a `reset` method and edit the `subscribe` method to add a `change` event listener, simply telling Shiny to get the new value. Contrary to `click`, `change` does not increment the button value, which is exactly what we want.
```{r, echo=FALSE, results='asis'}
js_code <- "$.extend(
Shiny
.inputBindings
.bindingNames['shiny.actionButtonInput']
.binding, {
reset: function(el) {
$(el).data('val', 0);
},
subscribe: function(el, callback) {
$(el).on('click.actionButtonInputBinding', function(e) {
let $el = $(this);
let val = $el.data('val') || 0;
$el.data('val', val + 1);
callback();
});
// this does not trigger any click and won't change
// the button value
$(el).on('change.actionButtonInputBinding', function(e) {
callback();
});
}
});"
code_chunk_custom(js_code, "js")
```
The whole JS code is found in the `{OSUICode}` package (see https://github.com/DivadNojnarg/outstanding-shiny-ui-code/blob/b95f656bce9de7600c05b5045a4e005f70c4f83d/inst/input-system/input-bindings/editBinding.js#L1) and below is the related app. It is available as an HTML dependency with `OSUICode::editBindingDeps()`, whose output is shown Figure \@ref(fig:edit-binding-demo).
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/edit-binding-client", view_code = FALSE), "r")
```
```{r edit-binding-demo, echo=FALSE, fig.cap='Edit and trigger an input binding from the client.', out.width='75%', fig.align='center'}
knitr::include_graphics("images/survival-kit/edit-binding-demo.png")
```
This trick has been extensively used in the [virtual physiology simulator](https://community.rstudio.com/t/shiny-contest-submission-a-virtual-lab-for-teaching-physiology/25348) to trigger [animations](https://dgranjon.shinyapps.io/entry_level/).
Another example of accessing a binding method from the client is found in the `{shinydashboard}` [package](https://github.com/rstudio/shinydashboard/blob/dc1e15b39b7198286373643e8e4417867548c467/srcjs/sidebar.js#L29).
## Secondary inputs {#secondary-inputs}
The Shiny input binding system is too convenient to be only used for __primary__ input elements like `textInput()`, `numericInput()`. It is a super powerful tool to unleash apps's __interactivity__. In the following, we show how to add an input to an element that was not primarily designed to be a user input, also non-officially denoted as __secondary__ inputs.
::: {.warningblock data-latex=""}
By convention, we'll not use `inputId` but `id` for secondary inputs, which is the case in all the new versions of RinteRface packages like `{bs4Dash}`.
:::
### Boxes on steroids {#boxes-on-steroids}
You may know the `{shinydashboard}` `box` function. Boxes are containers with a title, body and footer, as well as optional elements. Those boxes may also be collapsed. It would be nice to capture the state of the box in an input, so as to trigger other actions as soon as this input changes. Since an input value is unique, we must add an `id` parameter to the box function. Below is what we had to modify compared to the `shinydashboard::box()` function.
```{r, eval=FALSE}
box <- function(.., id = NULL, title = NULL, footer = NULL,
background = NULL, width = 6, height = NULL,
collapsible = FALSE, collapsed = FALSE) {
# ....; Extra code removed
tagList(
boxDeps(), # required to attach the binding
div(
class = if (!is.null(width)) paste0("col-sm-", width),
div(
id = id, # required to target the unique box
class = boxClass, # required to target all boxes
# ....; Extra code removed (box header, body, footer)
)
)
)
}
```
`boxDeps()` contains the JS dependencies to handle the box behavior.
```{r, eval=FALSE}
boxDeps <- function() {
htmlDependency(
name = "boxBinding",
version = "1.0.0",
src = c(file = system.file(
"input-system/input-bindings",
package = "OSUICode"
)),
script = "boxBinding.js"
)
}
```
As we may collapse and uncollapse the box, we create the `updateBox()` function, which will toggle it. In this example, it does not send any specific message since we'll rely on internal AdminLTE JS methods to do the work.
```{r}
updateBox <- function(
id,
session = getDefaultReactiveDomain()
) {
session$sendInputMessage(id, message = NULL)
}
```
If you play with this [example](https://adminlte.io/themes/AdminLTE/index2.html) and inspect a box as shown in Figure \@ref(fig:inspect-adminlte-box), you'll notice that when collapsed, a box gets the `collapsed-box` class, which is useful to keep in mind for the input binding design.
```{r inspect-adminlte-box, echo=FALSE, fig.cap='Collapsed AdminLTE2 box.', out.width='100%'}
knitr::include_graphics("images/survival-kit/inspect-adminlte-box.png")
```
This is time to design the JS dependency, that is, `boxBinding.js`. Like all input bindings, it starts by instantiating a new object with `Shiny.InputBinding()`. At the end of the code, we register the binding so that Shiny knows it exists.
```{r, echo=FALSE, results='asis'}
js_code <- "let boxBinding = new Shiny.InputBinding();
$.extend(boxBinding, {
// Methods go here
});
Shiny.inputBindings.register(boxBinding, 'box-input');"
code_chunk_custom(js_code, "js")
```
The following are the main steps taken to design the binding.
1. `find`: there is nothing special to say, we are looking for elements having the `box` class.
```{r, echo=FALSE, results='asis'}
js_code <- "find: function(scope) {
return $(scope).find('.box');
}"
code_chunk_custom(js_code, "js")
```
2. `getValue`: we check if the element has the `collapsed-box` class and return an object, which will give a list in R. This is in case we add other elements like the remove action available in AdminLTE. We therefore access each input element with `input$<box_id>$<property_name>`.
```{r, echo=FALSE, results='asis'}
js_code <- "getValue: function(el) {
let isCollapsed = $(el).hasClass('collapsed-box')
return {collapsed: isCollapsed}; // this will be a list in R
}"
code_chunk_custom(js_code, "js")
```
3. `setValue`: we call the plug and play AdminLTE `toggleBox` method.
```{r, echo=FALSE, results='asis'}
js_code <- "setValue: function(el, value) {
$(el).toggleBox();
}"
code_chunk_custom(js_code, "js")
```
4. `receiveMessage`: we call the `setValue` method and trigger a change event so that Shiny knows when the value needs to be updated within `subscribe`.
```{r, echo=FALSE, results='asis'}
js_code <- "receiveMessage: function(el, data) {
this.setValue(el, data);
$(el).trigger('change');
}"
code_chunk_custom(js_code, "js")
```
5. `subscribe`: as previously mentioned, it is necessary to know when to tell Shiny to update the value with the `subscribe` method. Most of the time, the change event might be sufficient, but as `{shinydashboard}` is built on top of [AdminLTE2](https://adminlte.io/docs/2.4/js-box-widget), it has an API to control the box behavior. We identify two events corresponding to the collapsible action:
- expanded.boxwidget (Triggered after the box is expanded)
- collapsed.boxwidget (Triggered after the box is collapsed)
After further investigations, those events are not possible to use since the AdminLTE library does not trigger them in the main JS [code](https://github.com/rstudio/shinydashboard/blob/dc1e15b39b7198286373643e8e4417867548c467/srcjs/AdminLTE/app.js#L577) (see the collapse method). There are other solutions, and we decided to listen to the `click` event on the `[data-widget="collapse"]` element and delay the `callback` call by a value which is slightly higher than the default AdminLTE2 animation to collapse the box (500 ms). If you omit this part, the input will not have time to properly update.
```{r, echo=FALSE, results='asis'}
js_code <- "subscribe: function(el, callback) {
$(el).on(
'click',
'[data-widget=\"collapse\"]',
function(event) {
setTimeout(function() {
callback();
}, 50);
});
$(el).on('change', function(event) {
setTimeout(function() {
callback();
}, 50);
});
}"
code_chunk_custom(js_code, "js")
```
6. Even though animations are nice, it might appear rather sub-optimal to wait 500 ms for a box to collapse. AdminLTE [options](https://adminlte.io/themes/AdminLTE/documentation/index.html#adminlte-options) allow you to change this through the `$.AdminLTE.boxWidget` object. We specify the `animationSpeed` property to 10 ms and update the input binding script to reduce the delay in the `subscribe` method (50 ms seems reasonable).
```{r, echo=FALSE, results='asis'}
js_code <- "$(function() {
// overwrite box animation speed.
// Putting 500 ms add unnecessary delay for Shiny.
$.AdminLTE.boxWidget.animationSpeed = 10;
});"
code_chunk_custom(js_code, "js")
```
We don't need an extra listener for the `updateBox()` function since it also triggers a click on the collapse button, thereby forwarding to the corresponding listener. The whole code may be found [here](https://github.com/DivadNojnarg/outstanding-shiny-ui-code/blob/b95f656bce9de7600c05b5045a4e005f70c4f83d/inst/input-system/input-bindings/boxBinding.js#L1).
Let's try our new toy in a simple app. The output is depicted in Figure \@ref(fig:toggle-shinydashboard-box).
```{r toggle-shinydashboard-box, echo=FALSE, fig.cap='{shinydashboard} box with custom input binding listening to the box collapse state.', out.width='50%', fig.align='center'}
knitr::include_graphics("images/survival-kit/toggle-shinydashboard-box.png")
```
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/boxes-on-steroids", view_code = FALSE), "r")
```
The `{bs4Dash}` box function follows the same principle, with extra features showed [here](https://github.com/RinteRface/bs4Dash/blob/6fb8f8175e3672bbb65236d76285c6310197f10c/srcjs/bs4Dash-2.0.0/cards.js#L2). We leave the reader to explore the code as an exercise.
### Further optimize boxes {#boxes-on-steroids-more}
We may imagine leveraging the input binding system to update any box property and get rid of the classic `renderUI()` approach. Indeed, until now, there would be only one way to update a box from the server. In the following code, we intentionally added a dummy task causing a 5 s delay in the card rendering. You'll notice that nothing happens for some time, which is weird for the end user and might cause you to think about a possible app crash (Figure \@ref(fig:update-shinydashboard-box), left side).
```{r, echo=FALSE, results='asis'}
code_chunk(OSUICode::get_example("input-system/update-box-renderUI"), "r")
```
```{r update-shinydashboard-box, echo=FALSE, fig.show = "hold", out.width = "50%", fig.align = "default", fig.cap='Left: what the user sees when app starts. Right: what the user sees after 5 s.'}
knitr::include_graphics("images/survival-kit/update-shinydashboard-box-1.png")
knitr::include_graphics("images/survival-kit/update-shinydashboard-box-2.png")
```
The whole piece of UI is re-rendered each time, while only the box class should be modified. As shown above, this does have substantial impact for a very complex app festooned with inputs/outputs, thereby altering the overall user experience.
Let's provide some optimization and get rid of the `renderUI()`.
Figure \@ref(fig:box-on-steroids-summary) summarizes the main idea, and you may use it as a mind map to follow the remainder of this section.
We proceed in two steps. The first part consists in customizing the previously designed `box()` function from \@ref(boxes-on-steroids) to gather as many parameters as possible in a list of options. For instance, we choose to extract `width` and `title`.
`width` is expected to be numeric, while `title` might be any HTML tag, a list of HTML tags, justifying the use of slightly more sophisticated code (we can't use `toJSON()` on a Shiny tag ... not yet). So that we don't shoot ourselves in the foot, we create a specific object for the processed `title`, that is, `processed_title`. Indeed, a common mistake would be to re-inject the processed title later in the HTML box tag, which would cause an error. Its purpose is solely to be part of the configuration script required by JS.
```{r, eval=FALSE}
box2 <- function(..., id = NULL, title = NULL, footer = NULL,
background = NULL, width = 6, height = NULL,
collapsible = FALSE, collapsed = FALSE) {
if (!is.null(title)) {
processed_title <- if (
inherits(title, "shiny.tag.list") ||
inherits(title, "shiny.tag")
) {
as.character(title)
} else {
title
}
}
props <- dropNulls(
list(
title = processed_title,
background = background,
width = width
)
)
# ....; Extra code removed
}
```
This properties list has to be treated on the JS side, the reason why we remove `NULL` elements with `dropNulls()`, since we don't want to send empty arrays. We choose the following approach, where we convert our properties to a JSON with `toJSON()` and embed them in a script tag. Note the `data-for` attribute pointing to the unique `id` parameter. This will guarantee the uniqueness of our configuration script.
```{r}
box2 <- function(..., id = NULL, title = NULL, footer = NULL,
background = NULL, width = 6, height = NULL,
collapsible = FALSE, collapsed = FALSE) {
# ....; Extra code removed
configTag <- tags$script(
type = "application/json",
`data-for` = id,
jsonlite::toJSON(
x = props,
auto_unbox = TRUE,
json_verbatim = TRUE
)
)
}
```
To create the box HTML tag, we leverage the `box()` function. The next step is to add the configuration tag, which is achieved with the new `{htmltools}` `tagQuery()` API, extensively studied in section \@ref(htmltools-modern). We finally attach the not-yet-designed JS dependencies with `tagList()`.
```{r, eval=FALSE}
box2 <- function(..., id = NULL, title = NULL, footer = NULL,
background = NULL, width = 6, height = NULL,
collapsible = FALSE, collapsed = FALSE) {
# ....; Extra code removed
boxTag <- tagQuery(
box(
..., id = id, title = title, footer = footer,
background = background, width = width, height = height,
collapsible = collapsible, collapsed = collapsed
)
)$
append(configTag)$
allTags()
tagList(box2Deps(), boxTag)
}
```
Like in \@ref(boxes-on-steroids), we define the new dependencies, namely `box2Deps()`, referencing the `boxBindingEnhance.js` script, which we are going to design in few minutes.
```{r, eval=FALSE}
box2Deps <- function() {
htmlDependency(
name = "boxBinding",
version = "1.0.0",
src = c(file = system.file(
"input-system/input-bindings",
package = "OSUICode"
)),
script = "boxBindingEnhanced.js"
)
}
```
Then, we have to modify the `updateBox()` function such that it handles both toggle and update possibilities. `options` contains all changeable properties like `title` and `width`.
We don't describe the toggle case since it is quite similar to the previous implementations. When the action is `update`, we enter the `if` statement and options must be processed. If the option element is a Shiny tag or a list of Shiny tags (`tagList()`), we convert it to character with `as.character()`. The returned message is a vector containing the action as well as the option list:
```{r, eval = FALSE}
updateBox2 <- function(
id,
action = c("toggle", "update"),
options = NULL,
session = getDefaultReactiveDomain()
) {
# for update, we take a list of options
if (action == "update") {
# handle case where options are shiny tag
# or a list of tags ...
options <- lapply(options, function(o) {
if (inherits(o, "shiny.tag") ||
inherits(o, "shiny.tag.list")) {
o <- as.character(o)
}
o
})
message <- dropNulls(
c(
action = action,
options = list(options)
)
)
session$sendInputMessage(id, message)
} else if (message == "toggle") {
session$sendInputMessage(id, message = match.arg(action))
}
}
```
Let's define the new JS binding required by `box2Deps()`. We start from the previously defined binding in `boxBindings.js` and modify the `setValue` method to import our newly defined properties. The `boxTag` has two children, the box and the configuration script. `$(el)` refers to the box, therefore we have to look one level up to be able to use the `find` method (find always goes deeper in the DOM), namely `$(el).parent()`. From there, we only have to target the script tag `$(el).parent().find('script[data-for="' + el.id + '"]')`. In practice, you may reuse this piece of code in multiple places, for instance in the `getValue` method. To avoid duplication, we create an internal function, `_getConfig`. Note the `_` prefix, which makes the difference between the default input binding methods (available for all bindings) and the user-defined methods, local to a specific binding. This function just returns the config script:
```{r, echo=FALSE, results='asis'}
js_code <- "_getConfigScript: function(el) {
return(
$(el)
.parent()
.find('script[data-for=\"' + el.id + '\"]')
)
}"
code_chunk_custom(js_code, "js")
```
We also extract the `_processConfig` method that calls `_getConfigScript` and converts the script content to a JS object that we can manipulate. Notice the `this` keyword: it represents the input binding instance as explained in section \@ref(input-binding-steps).
```{r, echo=FALSE, results='asis'}
js_code <- "_processConfig: function(el) {
return(
JSON.parse(
this
._getConfigScript(el)
.html()
)
)
}"
code_chunk_custom(js_code, "js")
```
Then, we call `_processConfig` inside `setValue`:
```{r, echo=FALSE, results='asis'}
js_code <- "setValue: function(el, value) {
let config = this._processConfig(el);
}"
code_chunk_custom(js_code, "js")
```
From the above code, `config.width` returns the initial width, while `value.options.width` contains the new width value provided in the `updateBox2` message output. As a security, we don't want to change `config` if the action provided in `updateBox2` is not `update` (see if statement). Assuming `value.action === "update"`, we can continue to develop our JS logic. Good practice is to check whether `value.options.width` exists with `value.options.hasOwnProperty("width")`. If yes, we ensure whether its value and `config.width` are different. We always choose `===`, which compares the type and the value (`==` only compares the value such that `"1" == 1` is `true`):
```{r, echo=FALSE, results='asis'}
js_code <- "setValue: function(el, value) {
let config = this._processConfig(el);
if (value.action === 'update') {
if (value.options.hasOwnProperty('width')) {
if (value.options.width !== config.width) {
this._updateWidth(
el,
config.width,
value.options.width
)
config.width = value.options.width;
}
}
// other items to update
}
}"
code_chunk_custom(js_code, "js")
```
`_updateWidth` is a internal method defined in the input binding. It has three parameters, `el`, `o` and `n` (o and n being the old and new values, respectively):
```{r, echo=FALSE, results='asis'}
js_code <- "_updateWidth: function(el, o, n) {
// removes old class
$(el).parent().toggleClass('col-sm-' + o);
$(el).parent().addClass('col-sm-' + n);
// trigger resize so that output resize
$(el).trigger('resize');