Glad you are trying it out!
It is possible for sure. In essence, ModelTxt is just an object with a render()
method like this:
render(el) {
// Create its own span element
this.span = document.createElement('span');
// Get the text by calling the provided callback with the model
let text = this.callback(this.model);
this.span.textContent = text;
// Append the span to the provided DOM element
el.appendChild(this.span);
// Listen to changes on the element
this.model.on('change', this.onChange);
return this.span;
}
onChange = () => {
// Set the text again in case it has changed.
// In ModelTxt, this is done with a fade animation,
// only if there was an actual change.
let text = this.callback(this.model);
this.span.textContent = text;
}
So, there isn’t much “magic” about ModelTxt. No real dependencies. The unrender
method is also simple: it just removes the span from the DOM and calls model.off
.
Writing your own slim component is quite easy as well, incase you don’t want the additional span
that ModelTxt wraps the text in, or if you want something else than the fade transition.
About using it in pre-rendered HTML. Let’s say you receive:
<body>
<ul>
<li id="item1">Initial text</li>
</ul>
</body>
Then, you can have a little javascript that “hi-jack” one of the elements:
client.get('library.book.1', book => {
// Get the element to hi-jack
let el = document.getElementById('item1');
// Delete all pre-rendered content, if you want to. Not needed.
while (el.lastChild) el.removeChild(el.lastChild);
// Create a ModelTxt and render it inside the element.
let component = new ModelTxt(book, book => book.title);
component.render(el);
});
But it is good to understand that Modapp Components isn’t really a framework, just some interfaces. It was a defined way by which we decided to create vanilla Javascript components. We built components as we needed them, using the basic Elem component to avoid boilerplate (annoying to have to write document.createElement('div')
all the time!).
And it has worked out amazingly well, actually. The concept of components that are capable of rendering themselves, and in the case of resource components such as ModelTxt, also updating themselves, has been really smooth!
Hope your attempts works out fine!
Best regards,
Samuel