Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active November 15, 2017 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/3d708d486ef8cbcbdb5c6cf932b6e9c7 to your computer and use it in GitHub Desktop.
Save tommcfarlin/3d708d486ef8cbcbdb5c6cf932b6e9c7 to your computer and use it in GitHub Desktop.
[WordPress, JavaScript] Creating jQuery Components in WordPress
$.get(acme_ajax_object.ajax_url, {
action: 'get_data',
security: acme_ajax_object.security
}, function(response) {
// More to come...
});
var $container = $('#component-container'),
i, l = 0;
$.get(acme_ajax_object.ajax_url, {
action: 'get_data',
security: acme_ajax_object.security
}, function( response ) {
for( i = 0, l = response.data.length; i < l; i++ ) {
$container.append(
_createComponent(response.data[i])
);
}
});
/**
* Creates a component to be added from the DOM based on the incoming data.
*
* For the purposes of this function, we're assuming there are several properties
* on data of which we're already aware.
*
* @param data The object containing the properties we need for the component.
*
* @return The component created from the incoming data.
*/
function _createComponent(data) {
var title = data.title,
imageUrl = data.imageUrl,
description = data.description,
$component = $('<div />');
$component
.append(
$('<p />').text(title)
)
.append(
$('<img />').attr('src', imageUrl)
)
.append(
$('<p />').text(description)
);
return $component;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment