MVVM with Looser Data Bindings
It’s not uncommon for JavaScript developers from an MVC or MVP background to review MVVM and complain about its true separation of concerns. Namely, the quantity of inline data bindings maintained in the HTML markup of a View.
I must admit that when I first reviewed implementations of MVVM (e.g., KnockoutJS, Knockback), I was surprised that any developer would want to return to the days of old where we mixed logic (JavaScript) with our markup and found it quickly unmaintainable. The reality however is that MVVM does this for a number of good reasons (which we’ve covered), including facilitating designers to more easily bind to logic from their markup.
For the purists among us, you’ll be happy to know that we can now also greatly reduce how reliant we are on data bindings, thanks to a feature known as custom binding providers, introduced in KnockoutJS 1.3 and available in all versions since.
KnockoutJS by default has a data-binding provider, which searches
for any elements with data-bind
attributes on them such as in the below example.
<inputid="new-todo"type="text"data-bind="value: current, valueUpdate: "afterkeydown",enterKey: add"placeholder="What needs to be done?"/>
When the provider locates an element with this attribute, it parses it and turns it into a binding object using the current data context. This is the way KnockoutJS has always worked, allowing us to declaratively add bindings to elements that KnockoutJS binds to the data at that layer. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access