I am trying to create a dynamic page generator, which means having multiple pages rendered each with their own instance of a javascript class that will help things like searching and exporting table data.
So my class would be like this:
class Table(){
constructor(TableName, default){
this.TableName = TableName;
this.default = default
}
addObject(id, parent, onclick, icon){
parent.append("<img id='" + id + "' src='" + icon + "' onclick='" + onclick + "'>");
}
export(){
//export the data
}
}
I can use the addObject just fine as that’s triggered within a function call, not directly onto an onclick, but that addObject will add an export icon that should call the specific export function for that specific table, knowing which data set to pull from. So far, my efforts have not been fruitful.
const table = new Table;
table.addObject("export", "#toolbar", "table.export()", Icons.EXPORT)
This does not work, even if running table.export() does in the console, or if I pass in the actual function instead of it as a string and attach it using jQuery.
I’ve seen some examples that would rewrite the function as:
this.export = function () {
//code here
}
But the whole point is to be able to make the code easy to work with, and I feel like that could complicate it for developers writing new functions.
I’ve also attached it in jQuery with (and without) the binding:
$(document).on('click', '#export', function(){
table.export().bind(table)
});
Is there something I’m missing?
2
Answers
Ok maybe it is just a typo. Your instantiation of Table should be with parentheses
I don’t really know how you’re implementing this feature in your project…
But my guess is that your
parent
can’t reach youtable
constant (witch contains yourTable
object)… Thus not accessing it’sexport
method…The following approach will let the interpreter handle the accessibility to the desired handler function for clicks. It’s functional.
In your original code the
addObject
appends a plain<img onclick='table.export()'>
to anyparent
. But the context that containsparent
can accesstable.export()
? What if if in yourparent
context thetable
symbol is any other thing than yourTable
instance? In your code there’s no way to know. That’s why you should avoid implementing youronclick
callbacks in plain text.