Skip to content
Kwasi Yonkopa edited this page Jul 19, 2019 · 8 revisions

Binding events

Use Dash.bind method to bind events to elements, without this or any other library for delegated events, your events won't fire on elements within your Contents Wrapper since they are added asynchronously.
Syntax

Dash.bind(event, parentSelector, elementSelector, listener(e));

Parameters
event
  The DOM event to bind

parentSelector
  Selector of any parent element guaranteed present immediately after DOMContentLoaded

elementSelector
  Selector of element to bind the event to

listener
  A callback function to be called on event firing.

Example

Dash.bind('click', 'body', '#content .users li', function(e) {
    console.log(e, this);
});

Note that you can access the actual e.currentTarget via the this reference.

Via data-action HTML attribute

You can bind click events to elements easily with the data-action attribute. Add a data-action html attribute to the elements you'd like to bind the event to, set its value to a function name and then define the function in your script as shown below.

HTML Content

<button id="click-me" data-action="openImageUploadBox"></button>

In your script define openImageUploadBox via the Dash.actions object

Dash.actions.openImageUploadBox = function(e){
    // This function will be called when you click on button#click-me, that's it!
}

This method comes in handy for

Binding data

You can bind data stored in the DOM to placeholder elements easily with Dash.bindData, to set up a relationship, use the HTML attribute data-name passing the same value for corresponding placeholders.

Syntax

Dash.bindData(bindFrom, placeholderElement);

Parameters
bindFrom
  The element from which data will be copied, contains child elements with data-name attributes

placeholderElement
  The element which data will be copied to, contains child elements with data-name attributes

Example
HTML content

<ul id='dropdown'>
    <li>
        <em data-name="sender">Paul Duse</em> 
        <a data-name="content">Hello World!</a>
    </li>
    <li>
        <em data-name="sender">John Doe</em> 
        <a data-name="content">Hello All!</a>
    </li>
</ul>

<div id="view-notes" class="bind-to">
    <div class="content">
        <h6 data-name="sender"></h6>
        <p data-name="content"></p>
    </div>
</div>

Javascript content

Dash.bind('click', 'body', '#dropdown li', function(e) {
    Dash.bindData(this, document.querySelector('#view-notes'));
});

Notice the data-name attribute in the HTML above, your HTML structure doesn't matter, neither does the type of element used. This is very useful when you have a list of items with lots of embedded data and want to expand that data in a viewer/modal or even pre-fill a form with that data for editing

Clone this wiki locally