3.6 KiB
Building Inputs
If you have some knowledge of HTML/CSS/JavaScript, you can create your own custom input components that can be reused by others.
Shiny input components should try to adhere to the following principles, if possible:
- Designed to be used from HTML and R: Shiny user interfaces can either be written using R code (that generates HTML), or by writing the HTML directly. A well-designed Shiny input component will take both styles into account: offer an R function for creating the component, but also have thoughtfully designed and documented HTML markup.
- Configurable using HTML attributes: Avoid requiring the user to make JavaScript calls to configure the component. Instead, it's better to use HTML attributes. In your component's JavaScript logic, you can easily access these values using jQuery (or simply by reading the DOM attribute directly).
Each custom input component you design needs an input binding, an object you create that tells Shiny how to identify instances of your component and how to interact with it. An input binding object needs to have the following methods:
-
find(scope) -
Given an HTML document or element (
scope), find any descendant elements that are an instance of your component and return them as an array (or array-like object). The other input binding methods all take anelargument; that value will always be an element that was returned fromfind.<p> A very common implementation is to use jQuery's <code>find</code> method to identify elements with a specific class, for example: </p>exampleInputBinding.find = function(scope) { return $(scope).find(".exampleComponentClass"); }; -
getId(el) -
Return the Shiny input ID for the element
el, ornullif the element doesn't have an ID and should therefore be ignored. The default implementation inShiny.InputBindingreads thedata-input-idattribute and falls back to the element'sidif not present. -
getValue(el) -
Return the Shiny value for the element
el. This can be any JSON-compatible value. -
setValue(el, value) - Set the element to the specified value. (This is not currently used, but in the future we anticipate adding features that will require the server to push input values to the client.)
-
subscribe(el, callback) -
Subscribe to DOM events on the element
elthat indicate the value has changed. When the DOM events fire, callcallback(a function) which will tell Shiny to retrieve the value.We recommend using jQuery's event namespacing feature when subscribing, as it makes unsubscribing these events later very easy. An example:
exampleInputBinding.subscribe = function(el, callback) { $(el).on("change.exampleComponentName", function(event) { callback(); }); };Later on, we can unsubscribe
".exampleComponentName"which will remove all of our handlers without touching anyone else's. -
unsubscribe(el) -
Unsubscribe DOM event listeners that were bound in
subscribe.Example:
exampleInputBinding.unsubscribe = function(el) { $(el).off(".exampleComponentName"); };