I have looked at the several questions on the use of self
in Javascript, and I don't believe that any of them answer my question - which is specifically how to create self
in an ES6 class
(not ES5, and not working in Angular).
I am trying to use self
in the callback function in an ES6 class. The only framework I'm using is jQuery. I know I need to use self
, but I don't know how to create a self
variable in an ES6 class.
<!-- BEGIN HTML -->
<div id="Header">
I want header-message.html to render here...
</div>
<div id="Footer">
I want footer-message.html to render here...
(But currently, both HTML chunks will appear here)
</div>
<script src="call/to/jquery.js"></script>
<script type="module" src="main.js"></script>
<!-- END HTML -->
// BEGIN main.js
import {ContentAsServiceClass} from './contentAsAService.js';
$(function() {
$('<div id="HeaderContent"></div>').appendTo('#Header');
let headerContent = new ContentAsServiceClass(
{
$htmlTargEl: $('#HeaderContent'),
htmlFileName: 'header-message.content.html'
}
);
headerContent.renderContent();
$('<div id="FooterContent"></div>').appendTo('#Footer');
let footerContent = new ContentAsServiceClass(
{
$htmlTargEl: $('#FooterContent'),
htmlFileName: 'footer-message.content.html'
}
);
footerContent.renderContent();
});
// END main.js
// BEGIN contentAsAService.js
export let ContentAsServiceClass = class {
constructor(
{
// defaults:
$htmlTargEl = null,
htmlFileName = ''
} = {
// override defaults:
$htmlTargEl: $htmlTargEl,
htmlFileName: htmlFileName
}
) {
// assign values to instance of object:
this.$htmlTargEl = $htmlTargEl,
this.htmlFileName = htmlFileName;
self = this;
// assigns `self` to `window` object - which I DON'T want,
// and will not work here! But how do I assign `this` to `self` in an ES6 class?
// Assigning to `var` (`var self = this`) does not work here.
}
appendHtmlContent(response) {
// I know I need to use `self` here.
if(!response || typeof response !== 'string') {
return false;
}
$(self.$htmlTargEl).append(response);
}
getHtmlContent() {
$.get(
'http://localhost/content/my-bucket/' + this.htmlFileName
).then(
this.appendHtmlContent
);
}
renderContent() {
this.getHtmlContent();
}
}
export default ContentAsServiceClass;
// END contentAsAService.js