Rivet API
This is a technical summary of what is offered by our Rivet API and how to create your own custom JS based elements within Cornerstone.
Rivet is our internal JS library that facilitates in building custom elements with JS. You can access this through window.csGlobal.rivet
in Global or Post JS, or through a script you load externally of the Cornerstone App.
rivet.attach
rivet.attach
will run code on an element based on a selector. It will run whenever Rivet has loaded and whenever another element with the same selector has been added to the page. When your selector is a data attribute, the second argument passed to your function will be the value of the data attribute for ease of use. The return of your function will be your teardown function or an array of teardown functions. When your element has been removed from the page these teardown functions are then run. This can help reduce and free memory in Cornerstone when the element is no longer on the page.
This function is useful because the Cornerstone App can dynamically add elements to the page and keeping up with changes can then be handled by Cornerstone internally. Letting you worry about functionality first.
// Simpler alias
const attach = window.csGlobal.rivet.attach;
// Attach to an element with the attribute `data-attribute-test`
attach('[data-attribute-test]', function(element, props) {
console.log('This is the element', element);
console.log('This is value of data-attribute-test', props);
// Teardown function
return function() {
console.log('This element has been removed from the page', element);
};
});
// Attach to any element that has the class `hide-on-click`
attach('.hide-on-click', function(element) {
// On click event
// Set the elements style display to 'none'
function onClick() {
element.style.display = 'none';
}
// Add event
element.addEventListener('click', onClick);
// Teardown remove the click event
// Since this element could be potentially removed this isn't necessarily needed
// However you could be adding events to the window or document.body
// and in that case you wouldn't want to keep the events attached
return function() {
element.removeEventListener('click', onClick);
};
});
See Also
See something inaccurate? Let us know