Sencha Inc. | HTML5 Apps

Blog

Ext JS 5: MVC, MVVM and More

May 20, 2014 | Arthur Kay

The Sencha Ext JS framework has become the industry standard for developing enterprise web applications thanks to its comprehensive widget library, powerful data package and robust tooling. Since the original Ext JS 1.0 release in 2007, a lot has changed in our industry — and web applications are certainly larger and more complicated than ever.

In 2010 Sencha released Touch 1.0, delivering the industry’s first JavaScript framework to address the architectural problems faced by large enterprise web applications by providing support for the MVC pattern. We then applied that feature to Ext JS 4.0 in 2011, helping to organize application code in the new world of enterprise web apps.

Because application architecture is as much about providing structure and consistency as it is about actual classes and framework code, building a good architecture unlocks a number of important benefits:

  • Every application works the same way, so you only have to learn it once
  • It’s easy to share code between apps, because they all work the same way
  • You can use build tools to create optimized versions of your applications for testing and production use

While Touch 1.0 and Ext JS 4.0 defined some best practices on how to structure your application using MVC, Ext JS 5 takes this concept to the next level by adding optional support for the MVVM architectural pattern. Although MVC and MVVM are in fact very similar software patterns, using MVVM has some specific benefits that can vastly reduce the amount of application logic developers need to write.

It is important to note that Ext JS 5 maintains full backwards compatibility with applications built with an MVC architecture. To help you understand what has and hasn’t changed, let’s take a deeper look at what the MVC and MVVM patterns do.

What is MVC?

Model-View-Controller (MVC) is an architectural pattern for writing software. It divides the user interface of an application into three distinct parts, helping to organize the codebase into logical representations of information depending upon their function.

MVC implementations may vary slightly between applications, but generally speaking each part of the architecture has specific responsibilities:

  • The Model describes a common format for the data being used in the application. It may also contain business rules, validation logic, and various other functions.
  • The View represents the data to the user. Multiple views may display the same data in different ways (e.g. charts versus grids).
  • The Controller is the central piece of an MVC application. It listens for events in the application and delegates commands between the Model and the View.

MVC: An Example

Let’s take a look at an example in Sencha Fiddle:

In this example, we see a simple MVC application involving a Master / Detail layout. The master view (an Ext.grid.Panel) contains records which, when selected, populate a related detail view (an Ext.form.Panel). Clicking the “Save” button (on the detail view) updates the record in the master view.

While this is a relatively simple example, you will notice that there is a lot of manual work in the controllers to manage component and model references — specifically for the detail view.

We will come back to this example in a moment to explore an alternate architecture.

What is MVVM?

Model-View-ViewModel (MVVM) is another architectural pattern for writing software that is largely based on the MVC pattern. The key difference between MVC and MVVM is that MVVM features an abstraction of a View (the ViewModel) which manages the changes between a Model’s data and the View's representation of that data (i.e. data bindings) — something which typically is cumbersome to manage in traditional MVC applications.

The MVVM pattern attempts to leverage the architectural benefits of MVC (separation of functional responsibilities) yet also provides the additional advantages of data binding. The result is that the Model and framework perform as much work as possible, minimizing (and in some cases eliminating) application logic that directly manipulates the View.

Elements of the MVVM pattern include:

  • The Model describes a common format for the data being used in the application, just as in the classic MVC pattern.
  • The View represents the data to the user, just as in the classic MVC pattern.
  • The ViewModel is an abstraction of the view that mediates changes between the View and an associated Model. In the MVC pattern, this would have been the responsibility of a specialized Controller, but in MVVM, the ViewModel directly manages the data bindings and formulas used by the View in question.

Keep in mind that not all Views in MVVM require a ViewModel, but when they are used, ViewModels are created for each related View, meaning that multiple instances might live simultaneously.

MVVM: An Example

Revisiting the previous example built with MVC, it seems that MVVM might solve some of the problems we had manually managing component and model references through data binding. In a revised example, built with Ext JS 5, we have replaced the Detail controller with a ViewModel to manage the data binding between the record and the two views sharing the record’s data.

We no longer need to click “Save”, and the record’s data is instantly updated everywhere thanks to two-way data binding. This saves us a lot of manual work and ultimately simplifies how large applications manage data.

What happened to Controllers in MVVM?

Despite the name Model-View-ViewModel, the MVVM pattern may still utilize Controllers — although one might choose to then call it an MVC+VM architecture. Confusing acronyms aside, the point here is that Ext JS 5 does not force you to choose between MVC and MVVM (see a hybrid example here).

Ext JS 4 introduced MVC Controllers in a global sense, and Ext JS 5 still supports that concept. However, Ext JS 5 also supports a new variation termed ViewController.

A ViewController is similar in nature to a ViewModel. Both constructs are scoped directly to the related View, eliminating much of the overhead required in traditional MVC to manage object references and restore application state.

ViewControllers are also similar to traditional (i.e. global) MVC Controllers from Ext JS 4 in that they listen for events and execute logic in response to those events. However, a major difference between ViewControllers and traditional Controllers is that individual ViewControllers are created for each related View, whereas Controllers are singular constructs listening globally across multiple Views.

ViewControllers and ViewModels participate in the Component lifecycle — meaning that for every instance of a View, unique instances of the configured ViewModel and ViewController are also created. The ViewModel and ViewController are subsequently destroyed when their associated View is destroyed.

On the one hand, this is great news because the application can (in theory) save memory and processing time by avoiding a more generic Controller, which would listen globally for events on Views that may not even exist. But on the other hand, it’s possible that memory use could grow due to multiple ViewModel and ViewController instances living simultaneously.

Lastly, keep in mind that not all Views in MVVM require a ViewController — they are completely optional.

Conclusion

Ext JS 4 paved the way for enterprise web applications to begin using MVC, defining a consistent architecture for organized code. Ext JS 5 has added support for MVVM while maintaining backwards compatibility for MVC, so developers should have no problems upgrading all apps built using Ext JS 4 to the latest version.

The best practices surrounding MVC architecture are still relevant in Ext JS 5, yet developers can now vastly reduce the amount of application logic necessary to build large and complex apps through two-way data binding.

This article is the first in a series surrounding the idea of application architecture, MVVM and data binding. Look for upcoming, detailed posts on ViewControllers and declarative listeners.

Resources:

There are 24 responses. Add yours.

frank

7 months ago

New tech that I want to know more!

MikeB

7 months ago

Thanks Arthur, great webinar…
MVVM is definitely something I need to look further into moving forward.

Swarnaprava Lenka

7 months ago

Thanks a lot Arthur for the great webiner ....I want to know more about Extjs 5

Peter Rietveld

7 months ago

Hi Arthur,

Great article with a clear approach of how it should be done. Unfortunately there is no viewcontroller which handles the save button in the ExtJs5 example. Could you implement this to enhance your app?

Leo

7 months ago

I think that MVVM is better than 4.2 MVC
with viewcontroller it’s easier develop modular views

Steve

7 months ago

I see in your Master controller code you made a comment about using controller ref and how they can be problematic?  Can you explain?  Thanks

  onGridSelect : function(grid, record, index, eOpts) {
      // grab a reference to the Detail view…
      // we could have used a controller “ref”, but those can also be problematic
      var detailView = Ext.ComponentQuery.query(‘form’)[0];
     
      //set the form record manually
      detailView.loadRecord(record);
  }

Arthur Kay Sencha Employee

7 months ago

@Steve

Saki explains the problem best on his blog: http://extjs.eu/blessing-and-curse-of-refs/

That’s ultimately one of the reasons why ViewControllers are so amazing, they don’t run into this problem.

Marc Gusmano

7 months ago

Arthur, is the seminar you did yesterday recorded?

TONY

7 months ago

In Detail controller in example,
      var record = detailView.getViewModel().getData().rec;
the record is retrieved from ViewModel.
But it can be still obtained from form’s getValues() method.
So what’s the pros when we using ViewModel?

Philip

7 months ago

Awesome architectural change!  Being enjoying MVVM in AngularJS… Now, ExtJS will be even more powerful.  Thanks Sencha!

Arthur Kay Sencha Employee

7 months ago

@Marc - The video is being uploaded now and will first be shared with those of you who registered for the webinar. We will then also share it publicly in a week or so.

@Tony - In that particular case, it probably wouldn’t matter. In theory the Form’s getValues() might differ greatly from the ViewModel’s getData(), so you’d just want to be careful.

Dirk Hamberger

7 months ago

If by MVVM the view (to edit a record) is directly bound to the record data, then how would you solve the problem of a record to be either committed or rejected (a user decides to “save” or “cancel”)?

Arthur Kay Sencha Employee

7 months ago

@Dirk - That would be a scenario to consider. My example was deliberately simple, but as you point out there could be implications to two-way data binding. However you’ll also notice that the record isn’t “saved” automatically in my second example… you’d still need to call record.commit() before those changes persisted.

arnoldvillasanta

7 months ago

Hi Arthur,

Most of the questions here are related to user prompts (go/no go), submit-like or cancel-like scenario, failed create/save rollback, single or batch create / update before commit, etc. 
It might go as far as what’s the equivalent of MVVM to MVC’s sync (success/failure) or store.load(callback) in 4.2.x…

It seems that using MVVM will have no much problem when manipulated data are for reference tables… but will go ugly if misused in transactional data.

Does Sencha have a use-case documentation to guide us, developers, to know what specific scenario MVVM solved that is troublesome in MVC;  what scenario should be left for MVC because MVVM is not good enough; and what must be moved from MVC to MVVM for code efficiency, data integrity, system performance and reusability of code.

arnoldvillasanta

7 months ago

Hi Arthur,

Also, if there are millions of records in the database, with 50++ field validations, how will MVVM handle the failures (single/batch commit)... if developer opt to use back-end validation rather than replicating them in javascript (front-end)...

Tom

7 months ago

Hi, the Japanese translation of this blog article is here: http://www.xenophy.com/sencha-blog/11110
Link to the Japan Sencha User Group: http://www.meetup.com/Japan-Sencha-User-Group/

Arthur Kay Sencha Employee

7 months ago

@arnoldvillasanta - Those are good questions, but unfortunately we don’t have detailed scenarios like that yet. We created MVVM to deal with some specific shortcomings of MVC (see the video from my webinar for more information, which will become public this week), but as Ext JS 5 is only in beta right now I can only speculate about the use cases you’ve asked about.

I honestly think that in many cases, MVVM makes the most sense in terms of reducing code complexity and increasing code reusability. In MVC, any of the UI change logic would be written by hand… so in MVVM it’s far simpler to implement. Having all the sync/load/validation handling you speak of won’t matter much, the data changes would just persist and be updated automatically through data bindings.

Arthur Kay Sencha Employee

7 months ago

For everyone subscribed to the comments, I’ve updated this post to embed the video from my webinar a few weeks ago. It’s also available via our Vimeo channel.

Vinojash

7 months ago

I always have a doubt, that is, In MVC pattern the View is getting data directly from Model then why you forgot to connect Model to View Connection.? its optional to involve controller in between Model and View. if I said wrong, sorry for that and plz give some explanation to this… Thank You…

Archit

6 months ago

Hi,
I am searching for web developer in Sammamish ,WA
Any of your friend is in search for job in Sammamish,WA may refer .

Job Title: Web Developer

Client: Microsoft
Location: Sammamish, WA

We are looking for a strong web developer to help us with our platform work.

Required Skills:

Front end technologies.
-      HTML5, CSS/CSS3, Javascript, BootStrap
-      LESS, AngularJS, RequireJs, TypeScript

Server Side technologies
          WebApi
          C#

Must Haves:

• Strong in front end technologies ,particularly with HTML, CSS and JavaScript.
• Must have designed and developed webpages and wireframes.
• Having worked with a MVVM and SPA
• MVVM based client development
• MVVM based javascript development

.(JavaScript must be enabled to view this email address)
425-608-0558

 

Rob

5 months ago

This is directed at the upcoming Architect release - specifically, with respect to upgrading an existing 4.2 Architect-developed application… perhaps it is a long-shot, but I’m hoping to get a jump on some upcoming work.

Assuming that one has a very simple application outlined in an Architect project, in ExtJS 4.2.x, will it be possible (theoretically, under simple and ideal conditions) to migrate it up to 5.x - or would one have to start from scratch?

If theoretically possible, are there specific considerations, restrictions, or things to avoid - i.e. avoid custom components, no easy MVC to MVVM switching, etc.

The use-case leading to this inquiry is that I would like to start building out some of the initial layout in 4.2 in an Architect project now, and then migrate it to 5.x when the update is available.  If it will not be possible (within Architect) under any reasonable circumstances, then I will drop the idea - or proceed anyway with the knowledge that I will have to rebuild it again later… But if it is, and highly conditional on some given conditions, then that would be useful info to know.

We’re not talking about full application building here - mainly layout work - so not a huge deal either way, but it would be great to know (in broad strokes) what might be possible.

 

 

Rob

5 months ago

Thanks @ArthurKay… couldn’t view the threads, even when signed in with my Sencha forums account.  I have an active subscription… I can browse the premium forums… have also tried forum searches for the threads you pointed to… perhaps I should follow up using a support ticket?

Arthur Kay Sencha Employee

5 months ago

@Rob - sorry about that, yes you might want to open a support ticket. I don’t know why you wouldn’t have access.

In short, you *should* be able to upgrade your projects from 4.2 > 5.0. That’s what we’re aiming for anyhow grin

The second link was for an Early Access Program, so I was going to suggest you give that a shot…

Comments are Gravatar enabled. Your email address will not be shown.

Commenting is not available in this channel entry.