I'm relatively new to JS world.
I am used to write UI with QT (great tools to build UI!). With the QT I'm doing a class for each element: If I have a table with some elements I have a class for each element and a class for the table (maybe also for the rows). Each class contains the data and the method for manipulating its "DOM".
Now in html I'm using some ejs files that contains an empty skeleton on the divs and I'm writing a class for manipulating it via jquery.
For example:
userslist.ejs:
<script type="text/javascript">
function UsersList(path) {
this.path = path;
$('#userList > tbody').empty();
this.loadAjax();
}
UsersList.prototype.loadAjax = function() {
var that = this;
$.getJSON(this.path, function(users) {
that.fillUsers(users);
});
};
UsersList.prototype.fillUsers = function(users) {
var that = this;
users.forEach(function(user){
var tr = that.buildTr(user);
$('#userList > tbody:last').append(tr);
});
};
UsersList.prototype.buildTr = function(user) {
...
};
</script>
<h1>Users list</h1>
<table id="userList">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Control</th>
</tr>
</thead>
<tbody></tbody>
</table>
With callback way of coding in JavaScript (and jquery dom manipulation in general) I easily lost the this
keyword to refer to class methods and class property (even if I earn some control in the nested callback). And I'm find myself to really abuse of the var that = this;
thing.. I have it in almost each method in the class.
How can I avoid this? I like OOP but I'm curious to explore this new trendy js, with some functional feature and with the asynch everywhere.
What is the correct way to handle this problem in JS? How can I avoid to write var that = this;
in each method every time I use a callback?