I have a library that's implemented using ES6 and I have an init method, when invoked draws a button on the view. And some internal changes takes place within a the "this.Object" variable. How can I expose the click event that's added to the button outside the Class scope so that the developer can have access to it ?
My Library Class
class Test {
constructor(selector) {
this.selector = document.querySelector(selector);
this.Object = {};
}
init(content = null) {
if (content == null) {
this.selector.innerHTML = `
<button id="test_btn" type="button">Click Me!</button>
`;
this.Object = {
'name': 'test'
};
this.button = document.getElementById('test_btn');
this.button.addEventListener('click', (event) => {
console.log(this.Object);
// how to return the variable value which is outside of the class Scope
});
} return this.selector, this.Object;
}
}
module.exports = (selector) => {
return new Test(selector);
};
When I use the library in the html, how can I get the value of "this.object" which is now an altered value within the init method and how to print the new value of "this.object" within the html content ?
Below is the html Code where I use my library
<body>
<div class="">Hello World</div>
<!-- minfied version of my library -->
<script src="build/Test.min.js" charset="utf-8"></script>
<script type="text/javascript">
// intialise library functionality
Test('div').init();
// console.log(this.new_Object)
// How to access the object from here
</script>
</body>
How can I expose the click event that's added to the button outside the Class scope so that the developer can have access to it ?
If the post needs more clarification, feel free to express your thoughts in the comments. Any help would be appreciated on this matter.
PS: This is traditional JavaScript and no jQuery is involved and I try to keep it that way
class Test {
constructor(selector) {
this.selector = document.querySelector(selector);
this.Object = {};
}
init(content = null) {
if (content == null) {
var self = this;
this.selector.innerHTML = `
<button id="test_btn" type="button">Click Me!</button>
`;
this.Object = {
'name': 'test'
};
this.button = document.getElementById('test_btn');
this.button.addEventListener('click', (event) => {
console.log(self.Object);
// how to return the variable value which is outside of the class Scope
});
}
}
}
//module.exports = (selector) => {
// return new Test(selector);
//};
// intialise library functionality
var test = new Test('div');
test.init();
console.log(test.Object)
// How to access the object from here
<body>
<div class="">Hello World</div>
</body>
When you call and event handler, the 'this' in the handler is set either the window or the element (depends on which browser). So in order to the the internal object via the click you have 2 options:
An example of point 1 above, which is the simplest.