Basic MVVM Architecture in JavaScript with knockoutjs

Basic MVVM Architecture in JavaScript with knockoutjs

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));

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:

Medium: https://medium.com/@nhannguyendevjs/

Dev: https://dev.to/nhannguyendevjs/

Hashnode: https://nhannguyen.hashnode.dev/

Linkedin: https://www.linkedin.com/in/nhannguyendevjs/

X (formerly Twitter): https://twitter.com/nhannguyendevjs/

Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs

Leave a Reply

Your email address will not be published. Required fields are marked *