JSFiddle - React, Tailwind, and code Playground
HTML
<p>Valeur de <em>test</em> : <span data-bind="test"></span>
</p>
<p>Valeur de <em>hello</em> : <span data-bind="hello"></span>
</p>
<select data-bind="test">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<label>
<input type="radio" value="1" data-bind="test" />1</label>
<label>
<input type="radio" value="2" data-bind="test" />2</label>
<label>
<input type="radio" value="3" data-bind="test" />3</label>
<br>
<label>
<input type="checkbox" value="1" data-bind="test" />1</label>
<label>
<input type="checkbox" value="2" data-bind="test" />2</label>
<label>
<input type="checkbox" value="3" data-bind="test" />3</label>
<br>
<input type="text" data-bind="hello" />
<br />
<textarea data-bind="hello"></textarea>
<hr>
<strong>Debug</strong>
<pre id="debug"></pre>
JavaScript
$(document).ready(function () {
// Un object JS simple pour stocker nos données
var model = {};
model.test = 1;
model.hello = 'Hello World';
// Mise à jour du model lorsque un élément change
$(document).on('change keyup', '[data-bind]', function () {
model[$(this).data('bind')] = $(this).val();
});
// On observe les changements du model
Object.observe(model, function (changes) {
changes.forEach(function (change) {
// Juste pour voir ce qu'il se passe
$('#debug').empty().append(change.type + "\n" + change.name + "\n" + change.oldValue);
// On déclanche la synchronisation
$('[data-bind=' + change.name + ']').trigger('bind');
});
});
// Syncronisation des champs
$(document).on('bind', '[data-bind]', function () {
var v = model[$(this).data('bind')];
// Pour les champs de type select
if ($(this).is('select')) {
$(this).children('[value=' + v + ']').prop('selected', true);
}
// Pour les champs de type choix uniques ou multiples
else if ($(this).is('input[type=radio], input[type=checkbox]')) {
$(this).prop('checked', $(this).val() == v);
}
// Les champs textes
else if ($(this).is('input, textarea')) {
$(this).val(v);
}
// Les autres balises
else {
$(this).text(v);
}
});
// On exécute au chargement du DOM l'événement pour initialiser tous nos champs
$('[data-bind]').trigger('bind');
});