JavaScript – Why is the Document Object Model the View?

domjavascriptmodelmvc

I was told by a Javascript programmer not to do DOM manipulation in model code.

I also remember hearing a snazzy tune for a JS framework (I forget which one): "Get your models out of the DOM".

This is confusing to me. The DOM is the Document Object Model. To me it sounds like "get your model out of the model".

Should my JS model really not touch the DOM? Can someone set me straight on model v. model?

Best Answer

There are a lot of overloaded terms in programming. The "model" in Model-View-Controller has nothing to do with the "model" in Document Object Model.

Arguably the DOM should have been called something like the Document Manipulation Interface, since that's what it actually is: an interface. More importantly, it's an interface for manipulating the content that gets shown directly to the user. In MVC, any code that shows things to the user should be in a View.

It's entirely correct to say that your MVC model should not be manipulating the DOM, for the same reason it shouldn't be generating popups or playing sounds: We want to keep the business entities (models) decoupled from the presentation logic.

Related Topic