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:

👋 Kindness is contagious

Please leave your appreciation by commenting on this post!

It takes one minute and is worth it for your career.

Get started

Community matters.

Top comments (3)

Collapse
 
artydev profile image
artydev

knockout "dead" but still relevant :-)

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 😁

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay