This is about the simplest demonstration possible without being Hello World. It creates an observable containing an integer. Then it binds a element to the observable, using it as a simple view model. The observable is incremented once a second for no reason other than to make something happen on the page.
This demo uses prototype extension methods to keep it as dead simple as possible. You need to load either the ichigo-full script or run the extensions module to create the "toObservable()" and "bindComponent()" methods.
Let's look at it statement by statement. There are only 3. The first statement builds the observable.
const observable = (0).toObservable();
This creates an ObservableProperty whose value begins as the number 0. The extension method being used here is the same as if you ran
const observable = new mi5.observable.ObservableProperty(0)
.
The number is surrounded by parentheses because numbers have periods too. Parentheses tell JS that you are running a method on the Number object, not building a malformed decimal.
On to statement 2 of 3.
document.getElementById('counter')
.bindComponent(observable)
.setTextTemplate()
.observe();
This binds the "counter" element to the observable you just created, using it as the view model. Again, this is using an extension method, and is the same as running
new mi5.component.BoundComponent(observable, { element: document.getElementById('counter') })
.
The call to setTextTemplate() with no arguments sets the text of the element, using the default value of '.' (which indicates the view model itself). The call to observe() subscribes the component's render() event to the observable's event handler.
The object is not rendered initially (update is not true when calling setTextTemplate()), meaning that for the first second, the value you see comes from the HTML, not the observable. Don't worry ... in one second, it will be re-rendered.
In statement 3, the observable is updated once a second using setInterval(() => observable.value++, 1000)
. This is standard JS. The only thing to point out here is that to read or write the value of an ObservableProperty, you must access the "value" property.
Component Extension Definition Observable Extension Definition