Fuxin Chen

Intel XDK PRC Team

MVC Frameworks

What is MVC Frameworks ?

MVC Pattern Overview

MVC offers architectural benefits over standard JavaScript — it helps you write better organized, and therefore more maintainable code.

This pattern has been used and extensively tested over multiple languages and generations of programmers.

MVC Pattern - Model

Model is where the application’s data objects are stored.

It matches up with the type of data a web application is dealing with, such as a user, video, picture or comment. The model doesn’t know anything about views and controllers. When a model changes, typically it will notify its observers that a change has occurred.

MVC Pattern - Model

The model here represents attributes associated with each todo item such as description and status. When a new todo item is created, it is stored in an instance of the model.

MVC Pattern - View

View is what's presented to the users and how users interact with the app. The view is made with HTML, CSS, JavaScript and often templates, usually access to the DOM.

MVC Pattern - View

In previous todo list web app, you can create a view that nicely presents the list of todo items to your users. Users can also enter a new todo item through some input format. However, the view doesn't know how to update the model because that’s the controller’s job.

MVC Pattern - Controller

The controller is the decision maker and the glue between the model and view. The controller updates the view when the model changes. It also adds event listeners to the view and updates the model when the user manipulates the view.

When user checks an item as completed, the click is forwarded to the controller.

The controller modifies the model to mark item as completed, and makes an async save to the server or local storage.

MVC Pattern - Controller

MVC Pattern - Variations 

Variations of the MVC design pattern:

  • MVP (Model–View–Presenter)
  • MVVP(Model–View–ViewModel)

Also some MVC–based frameworks will have the view observe the changes in the models while others will let the controller handle the view update.
No matter what implementations,they all focus on the separation–of–concerns and it's importance in writing modern web apps.

MVC Pattern

To summarize, the MVC pattern brings modularity to application developers and it enables:

  • Reusable and extendable code.
  • Separation of view logic from business logic.
  • Allow simultaneous work between developers who are responsible for different components (such as UI layer and core logic).
  • Easier to maintain.

MVC Frameworks

MVC frameworks are libraries that can be included alongside JavaScript to provide a layer of abstraction on top of the core language. Their goal is to help structure the code-base and separate the concerns of an application into Model, View and Controller three parts.

Why We Need MVC 

Frameworks ?

WHY ARE THEY NEEDED?

A DOM manipulation library such as jQuery coupled with utility libraries (underscore, modernizr) can make building webpages much easier. However, these libraries lose their usefulness when used to build web applications.

 

Web applications are unlike a normal web page, they tend to feature more user interaction as well as needing to communicate with a backend server in real time. If you were to handle this behaviour without an MVC framework you’d end up writing messy, unstructured, unmaintainable and untestable code.

WHEN SHOULD USE THEM?

You should consider utilizing an MVC framework if you're building an application with enough heavy-lifting on the client-side to struggle with JavaScript alone.

Be aware, if you’re just building an application that still has a lot of the heavy lifting on the server-side (i.e. view generation) and there is little interaction on the client-side, you’ll find using an MVC framework is likely overkill. 

Checklist to Use MVC?

  1. Your application needs an asynchronous connection to the backend
  2. Your application has functionality that shouldn’t result in a full page reload (i.e. adding a comment to a post, infinite scrolling)
  3. Much of the viewing or manipulation of data will be within the browser rather than on the server
  4. The same data is being rendered in different ways on the page
  5. Your application has many trivial interactions that modify data (buttons, switches)

Good examples that fulfil these criteria: Google Docs, Gmail.

Single Page Applications (SPA)

Glossary

Single Page Application generally refers to web applications based on the following characteristics:

  • Browser-based thick client backed by server side web services
  • Rich UI/UX constructed using advanced JavaScript & AJAX, HTML5, CSS, and responsive design
  • View composition and construction take place entirely on the client-side. Server side code is only used for retrieving and persisting application data

The application may contain several pages or views, but they are all sourced from a single HTML page from the server.

What is Backbone.js?

  • Created by Jeremy Ashkenas, the JS ninja who built CoffeeScript.
  • Backbone is a super light-weight library that lets you create easy to maintain front ends.
  • It makes it easy to manage and decouple concerns in your application, leaving you with code that is more maintainable in the long term.
  • Backbone.js are commonly use to create single-page applications (SPAs) for developers.
  • Backbone is mature, popular, and has both a vibrant developer community as well as a wealth of plugins and extensions available that build upon it.
  • Backbone has hard dependency on underscore.js and a soft dependency on jQuery.

What is Backbone.js?

It’s a library, rather than a framework, that plays well with others and scales well, from embedded widgets to large-scale applications.

Addy Osmani

What is Backbone.js?

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

—Official descripiton

What is Backbone.js?

Key-value binding and custom events:
When a model's contents or state is changed, other objects that have subscribed to the model are notified so they can proceed accordingly. Here, the views listen to changes in the model, and update themselves accordingly instead of the model having to deal with the views manually.

Rich API of enumerable functions:
Backbone ships with a number of very useful functions for handling and working with your data. Unlike other implementation, arrays in JavaScript are pretty neutered, which really is a hampering problem when you have to deal with data.

What is Backbone.js?

Views with declarative event handling:
Your days of writing spaghetti bind calls are over. You can programmatically declare which callback needs to be associated with specific elements.

RESTful JSON interface:
Even though the default method is to use a standard AJAX call when you want to talk to the server, you can easily switch it out to anything you need. A number of adapters have sprung up covering most of the favorites including Websockets and local storage.

What is Backbone.js?

Backbone provides a clean way to surgically separate your data from your presentation. The model that works with the data is only concerned with synchronizing with a server while the view's primary duty is listening to changes to the subscribed model and rendering the HTML.

  • Views
  • Events
  • Models
  • Collections
  • Routers

It’s made up of the following modules:

Models and Views

The single most important thing that Backbone can help you with is keeping your business logic separate from your user interface.

Model

  • Orchestrates data and business logic.
  • Loads and saves from the server.
  • Emits events when data changes.

View

  • Listens for changes and renders UI.
  • Handles user input and interactivity.
  • Sends captured input to the model.

Models and Views

A Model manages an internal table of data attributes, and triggers "change" events when any of its data is modified. Models handle syncing data with a persistence layer — usually a REST API with a backing database. Models should be able to be passed around throughout your app, and used anywhere that bit of data is needed.

Models and Views

A View is an atomic chunk of user interface. It often renders the data from a specific model, or number of models — but views can also be data-less chunks of UI that stand alone. Models should be generally unaware of views. Instead, views listen to the model "change" events, and react or re-render themselves appropriately.

Collections

A Collection helps you deal with a group of related models, handling the loading and saving of new models to the server and providing helper functions for performing aggregations or computations against a list of models.

Aside from their own events, collections also proxy through all of the events that occur to models within them, allowing you to listen in one place for any change that might happen to any model in the collection.

Routers

In rich web applications, we still want to provide linkable, bookmarkable, and shareable URLs to meaningful locations within an app. Use the Router to update the browser URL whenever the user reaches a new "place" in your app that they might want to bookmark or share. Conversely, the Router detects changes to the URL — say, pressing the "Back" button — and can tell your application exactly where you are now.

Events

Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments. For example:

var object = {};

_.extend(object, Backbone.Events);

object.on("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");

on binds a callback function to an object, off removes callback functions that were previously bound to an object and trigger triggers a callback for a specified event.

Events

While on() and off() add callbacks directly to an observed object, listenTo() tells an object to listen for events on another object, allowing the listener to keep track of the events for which it is listening. stopListening() can subsequently be called on the listener to tell it to stop listening for events:

// add listeners to A for events on B and C
a.listenTo(b, 'anything', function(event){ console.log("anything happened"); });
a.listenTo(c, 'everything', function(event){ console.log("everything happened"); });

// trigger an event
b.trigger('anything'); // logs: anything happened

// stop listening
a.stopListening();

// A does not receive these events
b.trigger('anything');
c.trigger('everything');

Dependencies

What this translates to is that if you require working with anything beyond models, you will need to include a DOM manipulation library such as jQuery or Zepto.

Underscore is primarily used for its utility methods (which Backbone relies upon heavily) and json2.js for legacy browser JSON support if Backbone.sync is used.

The official Backbone.js documentation states:

Backbone’s only hard dependency is either Underscore.js ( >= 1.4.3) or Lo-Dash. For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( >= 1.7.0) or Zepto.

Recommended Reading

Official documentation: http://backbonejs.org/

Developing Backbone.js Applications(By Addy Osmani)

What is Angular?

AngularJS as it says is a Superheroic  JavaScript MVW framework.It's created by Google to build properly architectured and maintainable web applications.

It assists with running single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier.

AngularJS takes declarative programming to whole new level. It adapts and extends traditional HTML to better serve dynamic content through two-way data-binding that allows for the automatic synchronization of models and views.

MVW – Model View Whatever

The most famous pattern that is used widely today is MVC . Similar to MVC, there are other patterns like MVP(Model-View-Presenter), MVVM(Model-View-View-Model).

Angular doesn't care what pattern you want to use.

A basic concept of MVW is that all definitions are associated with a named Module. Modules can then be aggregated to form complete web applications. Modules can depend on one another, so that including a single Module in your WebApplication may bring along additional functionality on which that Module depends. AngularJS provides you with rich set of APIs to define these modules and linked them together with dependency injection.

Hello World, AngularJS

<!DOCTYPE html>
<html ng-app>
<head>
    <title>Hello World, AngularJS - ViralPatel.net</title>
    <script type="text/javascript"
        src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
 
</head>
<body>
     
    Write some text in textbox:
    <input type="text" ng-model="sometext" />
 
    <h1>Hello {{ sometext }}</h1>
     
</body>
</html>

Please play around the code here.

ng-app

This attribute tells the Angular to be active in this portion of the page. If you want to enable Angular only at specific location in your webpage then you can define ng-app attribute to any DIV or other tag.

In case you are building app that also works with IE7, add id=”ngapp”. For example:

<!DOCTYPE html>
<html ng-app>
<head>
    <title>Hello World, AngularJS - ViralPatel.net</title>
    <script type="text/javascript"
        src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
 
</head>
<html ng-app id="ng-app">

ng-model

Attribute ng-model binds the state of textbox with a model value. Thus when textbox value changes, Angular automatically changes the model with this value. This is called Two way data binding. Similarly, if we change the model value then Angular will change the value of textbox.

The double curly braces tells Angular to bind the value of model sometext in place of {{ sometext }}.

AngularJS two-way data binding is its most notable feature.

<body>
    Write some text in textbox:
    <input type="text" ng-model="sometext" />
    <h1>Hello {{ sometext }}</h1>
</body>
<!DOCTYPE html>
<html ng-app>
<head>
    <title>Hello World, AngularJS - ViralPatel.net</title>
    <script type="text/javascript"
        src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
 
</head>
<body>
     
    Write some text in textbox:
    <input type="text" ng-model="sometext" />
 
    <h1 ng-show="sometext">Hello {{ sometext }}</h1>
     
</body>
</html>

Please play around the code here.

Hello World, AngularJS #2

ng-show / ng-hide

<body>
     
    Write some text in textbox:
    <input type="text" ng-model="sometext" />
 
    <h1 ng-show="sometext">Hello {{ sometext }}</h1>
     
</body>

ng-show attribute conditionally show an element, depending on the value of a boolean expression. Similar to ng-show you can also use ng-hide, which exactly does opposite of ng-show.

<!DOCTYPE html>
<html ng-app>
<head>
    <title>Hello World, AngularJS - ViralPatel.net</title>
    <script type="text/javascript"
        src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  
</head>
<body>
      
    Write some text in textbox:
    <input type="text" ng-model="sometext" />
  
    <h1>Hello {{ sometext }}</h1>
 
    <h4>Uppercase: {{ sometext | uppercase }}</h4>
    <h4>Lowercase: {{ sometext | lowercase }}</h4>
      
</body>
</html>

Please play around the code here.

Hello World, AngularJS #3

<body>
    Write some text in textbox:
    <input type="text" ng-model="sometext" />
    <h1>Hello {{ sometext }}</h1>
    <h4>Uppercase: {{ sometext | uppercase }}</h4>
    <h4>Lowercase: {{ sometext | lowercase }}</h4>
      
</body>

AngularJS provides powerful mechanism to modify the data on the go using Filters. Filters typically transform the data to a new data type, formatting the data in the process. The general syntax for using filter is:

AngularJS Filters

{{ expression | filter }}

You can use more than one filter on an expression:

{{ expression | filter1 | filter2 }}

AngularJS by default provide a lot filters that we can use in our app. It is also possible to define your own custom filters. 

AngularJS Filters

uppercase and lowercase:

This filter convert the expression into uppercase letters. 

date:

Formats date to a string based on the requested format. Read Angular documentation to know more about format.

{{ date_expression | date[:format] }} 

number:

Formats a number as text. If the input is not a number an empty string is returned.

{{ number_expression | number[:fractionSize] }} 

In order to create the views of your application, AngularJS let you execute expressions directly within your HTML pages. In those expressions, you have access to Javascript code which give you the ability to realize some computation in order to display what you want.

Expressions

Expressions are used for small operations, In order to structure your web application, AngularJS will give you a much impressive tool, directives.

Directives are one of the most powerful feature of AngularJS. They allow you to extend HTML to answer the needs of web applications. Directives let you specify how your page should be structured for the data available in a given scope.

Directives

AngularJS comes with several directives which let you build your basic application.

ngRepeat: This directive let AngularJS create a new set of elements in the dom for each element in a collection. 

Directives

Directives

*If you inspect the dom, you would see that the other elements have been computed but their are just hidden (display = none).

Directives

AngularJS also contains more complex directives like ngSwitch:

With those directives, you have the ability to define the basic structure of your web application very easily. 

Some directives can also be used as comments, DOM element's name or even CSS classes.

Custom Directives

 You can also create your very own directives in order to adapt your views to your needs.

If you need to have Javascript code in order to manipulate the DOM, it should not be located in a controller but in your own custom directive.

Using a custom directive is very easy.

Modules

In AngularJS, applications are structured in modules. A module can depend on other modules and a module can contain controllers, services, directives and filters.

The empty array, visible in the screenshot, is where you declare the modules needed by your module.

Dependency Injection

The operation “config” is using dependency injection in order to retrieve some elements of the application that should be configured when the module will be loaded. Here, we will use the service provider “$routeProvider” in order to define the routes of our application.

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies.

Routes

Using the route provider, we can configure the routes available in our application. For our example, we will only create two routes, one for our users “/users” and for any other routes, a redirection to our error page.

If we go to the url “http://domain/#/users”, AngularJS will load the partial view “views/users.html” and use the controller “UsersCtrl”. For any other url, the error view will be used instead. 

Controllers

In AngularJS, the controller is where the behavior of your application is located. Controllers are used to populate the scope with all the necessary data for the view. Controllers should never contain anything related to the DOM.

Controllers communicate with the view using a specific service named “$scope”. This service let the controller give objects and functions to the views that can later be manipulated with expressions and directives. In order to be easily tested, controllers are defined using dependency injection.

Scope

The scope is used to link the controllers and the views to which they are binded. A controller can add data and function in its scope and then they will be accessible in the view.

Scope

Watch

With the operation “$watch”, a controller can add a listener on an attribute of its scope to observe the changes.

Events

You can use the operation “$broadcast” in order to fire an event on a specific scope, then the event will be transmitted to the selected scope and all its children.

Summary

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

Source: Offical Wiki

What is React.js?

React is a UI library developed at Facebook to facilitate the creation of interactive, stateful & reusable UI components. It is used at Facebook in production, and Instagram.com is written entirely in React.

Many people choose to think of React as the V in MVC.

One of it’s unique selling points is that not only does it perform on the client side, but it can also be rendered server side, and they can work together inter-operably.

It also uses a concept called the Virtual DOM that selectively renders subtrees of nodes based upon state changes. It does the least amount of DOM manipulation possible in order to keep your components up to date.

Why React?

React is built to solve one problem: building large applications with data that changes over time. To do this, React uses two main ideas.

Simple
Simply express how your app should look at any given point in time, and React will automatically manage all UI updates when your underlying data changes.

Declarative
When the data changes, React conceptually hits the "refresh" button, and knows to only update the changed parts.

Page Setup

When setting up your page, you want to include react.js and JSXTransformer.js, and then write your component in a script node with type set to text/jsx:

<!DOCTYPE html>
<html>
  <head>
    <script src="build/react.js"></script>
    <script src="build/JSXTransformer.js"></script>
  </head>
  <body>
    <div id="mount-point"></div>
    <script type="text/jsx">
      // React Code Goes Here
    </script>
  </body>
</html>

The Basics

React’s basic building blocks are called components. Lets write one:

<script type="text/jsx">
    /** @jsx React.DOM */
    React.render(
        <h1>Hello, world!</h1>,
        document.getElementById('myDiv')
    );
</script>

If you haven't seen one of these before, you are probably wondering what Javascript/HTML chimera sorcery is taking place right now.

JSX

It is a Javascript XML syntax transform. This lets you write HTML-ish tags in your Javascript. Here HTML-ish means you are just writing XML based object representations.

For regular html tags, the class attribute is className and the for attribute is htmlFor in JSX because these are reserved words in Javascript. 

If you don't like JSX, here is what syntax looks like without it:

/** @jsx React.DOM */
React.render(
  React.DOM.h1(null, 'Hello, world!'),
  document.getElementById('myDiv')
);

Components

When using the render method above, the first argument is the component we want to render, and the second is the DOM node it should mount to.

var MyComponent = React.createClass({
    render: function(){
        return (
            <h1>Hello, world!</h1>
        );
    }
});
<script type="text/jsx">
    /** @jsx React.DOM */
    React.render(
        <h1>Hello, world!</h1>,
        document.getElementById('myDiv')
    );
</script>

We can use the createClass method to create custom component classes. 

Props

When we use our defined components, we can add attributes called props. These attributes are available in our component as this.props and can be used in our render method to render dynamic data:

var MyComponent = React.createClass({
    render: function(){
        return (
            <h1>Hello, {this.props.name}!</h1>
        );
    }
});

React.render(<MyComponent name="Handsome" />, document.getElementById('myDiv'));

State

Every component has a state object and a props object. State is set using the setState method. Calling setState triggers UI updates and is the bread and butter of React’s interactivity. If we want to set an initial state before any interaction occurs we can use the getInitialState method. Below, see how we can set our component’s state:

var MyComponent = React.createClass({
    getInitialState: function(){
        return {
            count: 5
        }
    },
    render: function(){
        return (
            <h1>{this.state.count}</h1>
        )
    }
});

Events

React also has a built in cross browser events system. The events are attached as properties of components and can trigger methods. Example.

/** @jsx React.DOM */
var Counter = React.createClass({
  incrementCount: function(){
    this.setState({
      count: this.state.count + 1
    });
  },
  getInitialState: function(){
     return {
       count: 0
     }
  },
  render: function(){
    return (
      <div class="my-component">
        <h1>Count: {this.state.count}</h1>
        <button type="button" onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
});

Unidirectional Data Flow

In React, application data flows unidirectionally via the state and props objects, as opposed to the two-way binding of libraries like Angular. This means that, in a multi component heirachy, a common parent component should manage the state and pass it down the chain via props.

Your state should be updated using the setState method to ensure that a UI refresh will occur, if necessary. The resulting values should be passed down to child components using attributes that are accessible in said children via this.props.

Questions?

MVC Framework

By fuxinchen

MVC Framework

  • 1,532