Wednesday, December 7, 2011

MVC in ExtJS - Why do we need a Model?

This blog post is based on how I understand now. I'll refine it in future.

Need for View and Controller

The need for View and Controller is relatively easy to understand (than the need for a model) in an ExtJS app. The arguments for separating View and Controller are the same here in ExtJS as well: separation of concerns. By isolating the controller logic from view, it is possible to reuse views, test them easily, etc.

Need for Model

The need for model in ExtJS may be slightly difficult to understand to a beginner.   It is because of the ambiguity surrounding the purpose of two different, yet similar objects - Store and Model, and when to use which object.

According to ExtJS help docs, "The Store class encapsulates a client side cache of Model objects."

It is like a C# datatable object that contains many rows of data. In this analogy, each row of data is a Model instance.

Store is always needed because it is the only way in which data can be stored on the client-side (browser) and be made available for consumption by many views.

Model is a choice. We may choose to create a model or choose not to create one.

If we choose to use a model, then each row of data in a Store is a Model instance and hence we will have access to validation, associations, etc. that are part of the Model.

Now, let us look at when we would need to create a model. But, first let us look at what components make up a Store object and a Model object.

 As you can see, both Model and Store share two properties: Fields and Proxy.

Proxy has two important properties: Reader and Writer. These are useful to fetch the data from the database /webserver and also to save any changes back to the data source.

Since proxy can be defined on Model or a Store, it is possible to do CRUD operations without a Model object!

Store also has fields collection. So, it is possible to databind a view to a Store and we do not need a Model object here as well.

So, it pretty much boils down to two scenarios when we would need a model:
(a) When we want to perform validations on the data before saving
(b) When we have hierarchical data and we want to navigate up and down the hierarchy at run time on the client side

Note: Even if we choose to create a Model, it is not a replacement for a Store. It is just that each row of data in the Store would now be a Model instance.

No comments:

Post a Comment