SoFunction
Updated on 2025-03-10

BackBone and its case study_System for Dynamic Node Java Academy

Introduction to MVC

Basic introduction

MVC is a model, view and control, which aims to realize the functional division of the web system. Specifically, it is to separate business logic and data display.

In MVC, the view provides interaction for users, the model is responsible for processing data and business logic, and the controller is the bridge of communication between the View and Model.

A very important sign of MVC is that the view (View) and the model (Model) do not interact directly, but communicate through the controller (Controller). Specifically: the user inputs through the View, the Controller is responsible for passing the input to the Model, the Model process, accessing data, and then the Controller returns the processed results to the View for display.

Pros and cons

The advantages of MVC architecture are significant, but there are also some disadvantages.

On the one hand, MVC can greatly reduce the coupling between data and views, have high maintainability and reusability, and can also improve division of labor efficiency and reduce life cycle costs, thus facilitating software engineering management.

However, the MVC architecture is not so easy to understand, and it will increase the complexity of the system and reduce the efficiency of view layer accessing the data layer, and is not suitable for the development of small projects.

Backbone

BackBone is an important front-end MVC framework for supporting heavyweight development of Javactript applications. The following will introduce the applications (closely related to the controller) and (closely related to the model), and combine examples to analyze how the Backbone framework supports the architecture of front-end MVC. All study materials come from the official website of BackBone:/


In Backbones, events can be used as a model of any object, and objects can bind and trigger an event named.

For an object declared (in the following discussion, all objects take object as an example), first add extend to object.

._extend(object,);

Then add an event to the object: the format is:

(event,callback,[context]);

The first parameter is the event name, and the second parameter is the callback function when the event is called.

The following event is an example: "alert" is the event name, function(msg) is the callback function, and msg is the parameter passed in when the event is triggered, which is consistent with the parameters in the trigger.

(“alert”,function(msg){alert(msg);});

The one that triggers the callback ("alert", "It's an event").

Similarly, the first parameter is the event name, while the second parameter passes in the parameters required by the callback function. Events are bound to an object through event names. You can see that this event does not need to be declared before binding, and the inherent connection in which the event can be triggered is the common object and event name. In particular, if the event is named "all", the callback function in it will be triggered whenever it is called.

Corresponding to standard event binding, the standard triggering format is:

(event,[*arg]);

You can also use similar attribute definitions in js to bind multiple events of an object, such as:

{
  “setup”:function_a(),
  “change”:function_b(),
  “destroy”:function_c()
}

When triggering the corresponding "setup", "change", and "destroy", the corresponding function_a(), etc. can be called respectively.

If you need to unbind an event on the object, use the (event, callback,[context]) function. The standard parameter list is consistent with the corresponding one.
Specifically, the above "setup":function_a() is an example:

 //Unbind (“setup”,function_a);
 
 //Remove all "setup" events (may bind multiple callback functions) (“setop”);
 
 //Remove all events of the binding function_a callback function (function_a);
 
 //Remove all events ()。

If you want the event to be unbinded once, use it directly(event,callback,[context])。

Use (other_object, event, callback), you can listen for events of other objects. When the event is triggered, the callback callback function is also called. Similarly, the standard stopListenTo([other_object], [event], [callback]) can be used to unbind.

ListenTo is very useful in MVC architecture, such as using view class objects to listen to the data processing events of the Model class and perform callbacks (usually displaying data).


Models is the core of a Javascript application. Many times, models need to process a lot of data, and the logic associated with this data. However, for JavaScript, there is no structure of a class like Java. However, in practical applications, such a model structure is needed. It provides a good expansion for js, allowing JavaScript to implement the structure and functions of classes, and to be more precise, implement properties similar to those in C#. Here is a simplified example officially introduced (for the sake of simplicity, all the introduced models then use Model, while the model objects use Models):

//Definition of similar classesvar Model = ({
  myData:”year2013”,
  myFunction:function(){myData = “year2014”;}
);

//Similar instantiation of similar classesvar model = new Model; 

// Similar object calls member methodsmy_class.myFunction();

You can see the above code to implement a similar class structure. The difference between properties of traditional javascript objects is that one is a concrete object (can only be used once), and the other is a model of a class (can be instantiated multiple times).

Since we already have the instantiation function of similar classes, we naturally provide us with an expansion of similar constructors. When an object is instantiated, it is instantiated using the standard format of new Model([attributes], [options]). For example:

new Model({
    myData:”2013”
});

In addition, the js of BackBone, like C#, also have properties of get and set functions. Calling similar to the following:

var date = (myData);
(myData,”2014”); 

In addition, many default functions of models have been expanded for js, and will not be introduced one by one. When you need to use it, it is recommended to use it on the official website/#Model-urlto query the Model.

BackBone instance: Todo

Let’s take a look at the specific application of BackBone in front-end MVC based on the example Todos given in the official website.

This is a pure JS implementation of task single application.

Four "classes" are designed in the code to implement the function of the task order:

//Model level, implement data operation of a taskvar Todo = ({});

//At the Model level, it realizes data operations of the entire taskbar, and Collection expands local storage functionsvar TodoList = ({});

//(), View and Controller levels//Responsible for receiving user operations and modifying Model data, displaying data in render() function
//Related to Todo's Dom elementvar TodoView = ({});
//The top level UI and controllervar AppView = ({});

First, we analyze the Model in the example and adopt a bottom-up analysis method:

Todo represents the task in each Todo. The logic related to it is whether it has been completed. You need to specify whether it has been completed. You need to specify the initial attribute done: false. In addition, you need to set the done function, add attributes for this:

toggle:function(){
  ({done:!(“done”);});
}

You can see that this property logically implements the View layer check box function in the data layer.

For TodoList, use Collection Model for local data storage.

The attribute contains model: Todo, that is, the lower-level, which implements an instance of a task.

In addition, localStorage : new ("todos-backbone") is required. Used for local storage.

In terms of data processing, the low-level done attribute needs to be encapsulated, done:function() is implemented, and the location of the changed done is returned.

At the View and Controller level, the following two "classes" are designed in sequence from bottom to top.

var TodoView = ({});
var AppView = ({}); 

First, for TodoView, a series of event responses are set. TodoView receives such event listening at the Controller level:

events: {
   "click .toggle"  : "toggleDone",
   "dblclick .view" : "edit",
   "click " : "clear",
   "keypress .edit" : "updateOnEnter",
   "blur .edit"   : "close"
} 

Taking clear() as an example, the data layer is called () in clear, which is fed back to the data layer.

clear: function() {
   ();
}

On the other hand, when initializing, TodoView is specified to listen to the data layer. When the change event occurs, TodoView occurs (the same is true for render), and this is the content of the presentation layer, which is feedback to the presentation layer.

initialize: function() {
   (, 'change', );
   (, 'destroy', );
}

This completes the MVC architecture from View (input) -> Controller -> Model (processing) -> Controller -> View (display). As can be seen from the above, all processes from the reception, processing, return, and display of data are automatic, and there is no coupling between View and Model. This is the standard MVC mode.

From TodoView upwards is the overall AppView. Its logical behavior is similar. It also receives data in the view layer, feeds it back to the data layer through the structure unique to the View class, and then the data layer returns the data to the view layer for display without coupling. However, as the top-level View and Controller, it implements overall rendering in the render function of the view layer, while the underlying rendering is handed over to TodoView, and the event response and event listening at the control layer are also implemented with higher encapsulation. If you add a todo, you will pass it in sequence as follows:

//View->Controller
"keypress #new-todo": "createOnEnter"

//Controller->Model
createOnEnter: function(e) {
   if ( != 13) return;
   if (!()) return;

   ({title: ()});
   ('');
}

//Model -> Controller
(Todos, 'add', );

//Controller -> View
addOne: function(todo) {
   var view = new TodoView({model: todo});
   this.$("#todo-list").append(().el);
}

In the last addOne function, the underlying MVC conversion process is included, but this is obviously not what we care about. It is encapsulated by the underlying layer and will automatically pass the MVC logic in the Backbone framework.

Todo summary

This is the structure of the entire Todo Totuorial. In general, the specific structure provided by BackBone for us well implements the MVC architecture and completes the separation of View and Model. Controller plays a very good role as a converter.

Experience

Since I have not learned the knowledge of front-end MVC before, I encountered many difficulties in exploring Todo instances. Todo instances are very different from traditional web applications:

a) No static html code, pure js implementation

b) The interaction principle between data and interface is very difficult to understand

c) The gap between the construction of View and the processing of data is too big.

d) Event listening and event binding purposes are different, and the response and callback processes are easily confused

At first, it was really difficult to understand Todo's structure, but later, in turn, think about the structure of MVC, start from the view, and explore clues about View->Controller->Model->Controller->View. This leads to the overall structure and the transmission process of the Controller. It can be said that understanding the Controller bridge plays a crucial role in the whole MVC structure. It is recommended to start with the input of the View and analyze the Controller.

On the other hand, top-down and bottom-up structures can be appropriately adopted for analysis. For example, when analyzing View, it is easier to start with the top-down method, while Models' bottom-up method can help us understand the structure of Models more clearly.