JSFiddle - React, Tailwind, and code Playground
HTML
<div class="body">
<button>
showForm();
</button>
</div>
<template class="form-template">
<form method="post">
<input type="text" name="random" value="123">
<input type="submit">
</form>
</template>
JavaScript
function Widget(view) {
this.view = view;
}
Widget.prototype.handleFormSubmit = function() {
this.view.form.submit(function(e) {
e.preventDefault();
this.view.showResult();
}.bind(this));
};
Widget.prototype.handleShowFormButton = function() {
this.view.button.click(function() {
this.view.showForm();
this.handleFormSubmit();
}.bind(this));
};
function View() {
this.body = $('.body');
this.button = $('button');
this.form = $('form');
}
View.prototype.showForm = function() {
if ($(this.form).length == 0) {
var template = $(".form-template").html();
$(this.body).append(template);
this.form = $('form');
} else {
$('input[name="random"]', this.form).val(Math.random());
}
}
View.prototype.showResult = function() {
$(this.body).append($("<p />").text("Random: " + $('input[name="random"]', this.form).val()));
};
var view = new View();
var widget = new Widget(view);
widget.handleShowFormButton();
for (var i = 0; i < 5; i++) {
$(view.button).click();
}
view.form.submit();