DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

5

Basic MVVM Architecture in JavaScript with knockoutjs

Image description

View
The view is a Graphic User Interface created using a markup language to represent data.

View binds to properties of a ViewModel through the data-bind concept, which indirectly connects to the model data.

View need not be changed for any alteration done in ViewModel.

Changes made to data in ViewModel are automatically propagated in View due to binding.

Model
A model is domain data or a business object that holds real-time data.

The model does not carry behaviors.

Behavior is mainly implemented in business logic.

ViewModel
ViewModel is the center place where data from Model and View's display logic are bundled together.

ViewModel holds the dynamic state of data.

There is an implicit binder between View and ViewModel to communicate with each other.

This binding is inclusive of declarative data and command binding.

Synchronization of View and ViewModel is achieved through this binding.

Any change made in View is reflected in ViewModel, and similarly any change in ViewModel gets automatically reflected in View.

The existence of this 2-way binding mechanism is a key aspect of this MVVM pattern.



const ViewModel = function (first, last) {
  this.firstName = ko.observable(first);
  this.lastName = ko.observable(last);

  this.fullName = ko.computed(function () {
    return this.firstName() + ' ' + this.lastName();
  }, this);
};

ko.applyBindings(new ViewModel('Planet', 'Earth'));


Enter fullscreen mode Exit fullscreen mode

A complete example here: https://stackblitz.com/edit/stackblitz-starters-ntxh9w?file=script.js


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (3)

Collapse
 
fyodorio profile image
Fyodor

Just curious, why knockout? It’s kinda dead…

Collapse
 
nhannguyendevjs profile image
Nhan Nguyen

I just use it to make a demo. We can use another 😁

Collapse
 
artydev profile image
artydev

knockout "dead" but still relevant :-)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!