Sha256: 42e8b138027d9b1febcbe84894c0256cfba6e241195e38811712c9abcf8b7bf6
Contents?: true
Size: 1.94 KB
Versions: 2
Compression:
Stored size: 1.94 KB
Contents
class addFields { // This executes when the function is instantiated. constructor() { this.links = document.querySelectorAll('.add_fields') this.iterateLinks() const event = new Event('works_cited:load') window.dispatchEvent(event); } iterateLinks() { // If there are no links on the page, stop the function from executing. if (this.links.length === 0) return // Loop over each link on the page. A page could have multiple nested forms. this.links.forEach(link => { link.addEventListener('click', e => { this.handleClick(link, e) }) }) } handleClick(link, e) { // Stop the function from executing if a link or event were not passed into the function. if (!link || !e) return // Prevent the browser from following the URL. e.preventDefault() // Save a unique timestamp to ensure the key of the associated array is unique. let time = new Date().getTime() // Save the data id attribute into a variable. This corresponds to `new_object.object_id`. let linkId = link.dataset.id // Create a new regular expression needed to find any instance of the `new_object.object_id` used in the fields data attribute if there's a value in `linkId`. let regexp = linkId ? new RegExp(linkId, 'g') : null // Replace all instances of the `new_object.object_id` with `time`, and save markup into a variable if there's a value in `regexp`. let newFields = regexp ? link.dataset.fields.replace(regexp, time) : null // Add the new markup to the form if there are fields to add. newFields ? link.insertAdjacentHTML('beforebegin', newFields) : null // Tell it new fields are there const event = new Event('works_cited:add_fields') window.dispatchEvent(event); } } // Wait for turbolinks to load, otherwise `document.querySelectorAll()` won't work window.addEventListener('load', () => new addFields()) window.addEventListener('works_cited:add_fields', () => new addFields())
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
works_cited-0.1.16 | app/assets/javascripts/works_cited/addFields.js |
works_cited-0.1.15 | app/assets/javascripts/works_cited/addFields.js |