JSFiddle - React, Tailwind, and code Playground
HTML
<div id='root'>
</div>
JavaScript
/**
* Person class
*/
var Person = new Class({
initialize: function(name) {
this.name = name;
},
setName: function(name) {
this.name = name;
}
});
/**
* Widget class
*/
var Widget = new Class({
initialize: function() {
this.view = new Element('div');
this.nameLabel = new Element('span', {text: ''});
this.nameInput = new Element('input', {type: 'text'});
// view:
//
// <div>
// <span></span>
// <input type='text' />
// </div>
this.view.adopt([this.nameInput, this.nameLabel]);
},
setName: function(name) {
this.nameLabel.set('text', name);
this.nameInput.set('value', name);
},
// inbuilt function
// basically bridges custom classes to DOM elements
// so we can directly add an object of widget to the page as in:
//
// var myWidget = new Widget(somePerson);
// $('page').append(myWidget);
toElement: function() {
return this.view;
}
});
/**
* Presenter class
* binds the view and the model together
*/
var Presenter = new Class({
initialize: function(person, widget) {
this.person = person;
this.widget = widget;
this.bind();
},
// bind model and widget together
// setup event handling, ajax calls, here
// so the reference to widget is intact
bind: function() {
this.widget.setName(this.person.name);
this.widget.nameInput.addEvent('keyup', function(event) {
var name = this.widget.nameInput.value;
// update model
this.person.setName(name);
this.widget.setName(name);
}.bind(this));
},
go: function() {
$('root').grab(this.widget);
}
});
// test-drive
var norris = new Person('Chuck Norris');
var bauer = new Person('Jack Bauer');
var norrisPresenter = new Presenter(norris, new Widget());
var bauerPresenter...