Reputation: 337
I don't know if "one-way data binding" is actually the correct definition, but I have a class called timesheetRow
, which represents a row in a table when called.
The class has a method called generateRow()
, which binds <td>
elements to the object properties and then appends all of them to a parent <tr>
element. I do it this way because before returning the row, I gotta add some event listeners for validation purposes. The code is like this:
class timesheetRow{
generateRow(){
this.row = htmlToElement(`
<tr>
</tr>
`);
this.nodes.workHours = htmlToElement(`
<td>
<input name="workHours"
min=0
max=24
class="form-control workHours"
type="number">
</td>
`);
this.nodes.workProject = htmlToElement(`
<td>
<select name="workProject"
class="form-control workProject"
required>
<option disabled selected value="">Sin proyecto asignado</option>
<option value="1">Proyecto 1</option>
</select>
</td>
`);
this.nodes.workHours.addEventListener("input", event => {
this.row.querySelector('.workProject').disabled = parseInt(event.target.value) < 1;
});
for (let node in this.nodes) {
this.row.appendChild(this.nodes[node]);
}
return this.row;
}
}
This is a very abridged version of the actual code, but I hope it will work to clarify my question.
If you take a look at the event listener I added to the workHours element, it works directly on the row stored as one of my object properties, but changing that property automatically changes the DOM as well. So, as far as I know, that looks like one-way data binding. When the workHours value is below 1, the workProject select element gets disabled. I'm not directly changing the DOM, I'm changing my object.
I would like to know what's going on behind the scenes here. Thanks in advance to anyone who takes the time to answer my question!
Upvotes: 0
Views: 160
Reputation: 10153
this.row.querySelector('.workProject')
returns a reference to a DOM Node, which is an object representing a DOM Node.
disabled
is a property on a select
Node which manipulates the way the browser renders it. The rendering engine itself knows it needs to redraw the input when you change that disabled
property.
There is no magic involved.
you type something in the input, an input
event is dispatched
you added an input
listener on the input
, so the listener gets called every time (1) happens
your listener gets a reference to the select
and changes a property on it
the browser/thing responsible for rendering DOM is designed in such a way that changing that disabled
property on select
s does what one expects
Also this.row.querySelector('.workProject') !== this.nodes.workProject
.
Upvotes: 1