DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

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:

I hope you found it useful. Thanks for reading. πŸ™

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

Top comments (3)

artydev profile image

knockout "dead" but still relevant :-)

fyodorio profile image

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

nhannguyendevjs profile image
Nhan Nguyen

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