FLUX vs MVC

FLUX vs MVC

The internet is abuzz with Facebook’s recently launched Flux, their new pattern to structure client-sided applications. Let’s take a look how the new Flux pattern relates to the earlier used MVC pattern and how it could end up being as useful as the user interface builder, React.

FLUX vs MVC

The story behind the model-view-controller(MVC) pattern and how numerous companies and projects have used it in the past is pretty interesting. It is recommended that you go through this brief history because it’s a great way to understand the specific domain that the Flux pattern operates under.

The MVC Pattern

Web developers have been using a lot of model-view-controller (MVC) patterns that have each being doing things a bit differently than the other. But, most MVC patterns typically perform the following core roles:

a. Model: This maintains the behavior and data of an application domain.
b. View: This represents the showcasing of the model in the user interface.
c. Controller: Taking user inputs, manipulating the model and prompting the view to update itself

The core concept of model-view-controller can be formulated by:

1. Separating the presentation from the model – This not only enables the implementation of varied UIs, but also ensures smoother testability.

2. Separating the controller from the view – This is extremely useful for older web interfaces that are not commonly used in most Graphic User Interface (GUI) frameworks.

Problems with MVC

Introduced in Smalltalk-76, the object-oriented, dynamic reflective programming language, MVC is an application pattern that is a legend in its own right as it has been employed for multiple projects ever since 1976. And even in 2015, it has firmly stood the test of time and is being used in some of biggest projects. So, the question arises as to why it should even be replaced! The truth is that MVC didn’t scale well when it came to Facebook’s enormous codebase. Major challenges arose due to Facebook’s bidirectional communication platform, where one change would loop back and have ripple effects across the entire code-base. This made the system fairly complicated and debugging almost impossible.

The Flux Pattern

MVC’s shortcomings posed some serious challenges, and Facebook solved them by incorporating Flux, which forces unidirectional flow of data between a system and its components. Typically, the flow within an MVC pattern is not well defined. Flux however, is completely dedicated to controlling the flow within an application, making it as simple to comprehend as possible.

The Flux pattern has four core roles including actions, storage, data dispatcher and views. Their functions are described below:

a. Actions – These are pure objects that consist of a type property and some data.
b. Stores/Storage - This contains complex data, including the application’s state and logic. One can consider stores as a manager for a particular domain within the application. While Flux stores can store virtually anything, they are not identical to MVC models because these models typically attempt to model single objects.
c. The Dispatcher – This essentially acts as the hubs nerve center. The dispatcher processes actions like user interactions and prompts loops that the storage has registered within it. And as with storage, the dispatcher is quite different from controllers in the model-view-controller (MVC) pat
tern. The difference is that the data dispatcher does not contain a lot of logic within it, allowing you to reuse the samedispatcher across a variety of new and complex projects.
d. Views – These are just controller-views and are also commonly found in most Graphic User Interface (GUI) MVC patterns. They monitor for any changes within the stores and re-design themselves accordingly in real time. Views also have the ability to add new actions to the dispatcher, user interactions included. These views are normally coded with React, but with Flux patterns it’s not necessary to use React. The typical flow of a Flux application can be defined in the below diagram.

It is critical to note that every change that you make will go through an action via the dispatcher.

So how does Flux differ from MVC?

1. The Flow

When it comes to Flux, the flow of the application is vital and these are governed by some strict rules and exceptions that are enforced by the data Dispatcher. In model- view-controller (MVC) patterns however, the flow is not strictly enforced or not enforced at all. This is why different MVC patterns implement their flows differently.

2. Unidirectional flow

As all changes go through the data dispatcher, stores/storage cannot change other stores directly and the same basic concept applies for views and other actions. So, any change has to go through the dispatcher via actions. And MVC’s commonly have bidirectional flow.

3. Stores

Flux stores can store any application related state or data. But, MVC models try to model single objects.

So, Is Flux better than MVC?

The fact that Flux has only recently been launched means that it’s too early to say as its perceived benefits are yet to be vetted. That being said, Flux is very new and innovative and it’s just refreshing that there is now a new pattern that can challenge MVC and its traditional ways.

The best part remains that Flux is extremely easy to understand and comes with minimalist coding, allowing you to structure your app in a more effective manner. This augers well for the future, particularly when React’s programming language is nefarious for coming with a nearly endless huge codebase and an even bigger runtime complexity that turns off a lot of web developers.

HOW REQUIREJS PLAYS A ROLE IN ANGULAR?

How RequireJS Plays a Role in Angular?

It’s the best way of simplifying the task of loading dependencies using AngularJS and RequireJS

One of the basic steps that need to be taken while writing big JavaScript apps is the division of the code base into numerous files. Not only does this help to enhance the maintainability of the code but it increases the possibility of misplacing or missing the script tag on the primary HTML document.

With the increase in the number of files, keeping up a clean record of all the dependencies becomes rather complicated and this issue extends to the case of large AngularJS apps as well. There are few tools that can handle the loading dependencies in the application.

It is important to know the best way of simplifying the task of loading dependencies by using RequireJS with AngularJS along with the way in which Grunt must be used for the purpose of generating combined files holding the RequireJS modules.

Understanding the Basics of RequireJS

RequireJS is a JavaScript library that assists with the loading of JavaScript dependencies at a slow pace. Modules are basically JavaScript files with a few RequireJS syntactic sugar in them and so, RequireJS is capable of implementing the Asynchronous Modules that are specified by the Common JavaScript. You attain the benefit of creating and referring to modules by using the simple APIs offered by RequireJS.

RequireJS should always have a main file that holds the basic configuration data like shims and path modules. The snippet below explains the basic outline of a main.js file:

require.config ( {
map: {
// Maps
},

paths: {
// duplicate names and path of the
modules
},
shim: {
// Modules, plus their dependent modules
}
} );

Every module present within the application does not need to be specified within the paths section and others may be loaded with the help of their relative paths. However, when defining a particular module, the define( ) block needs to be used.

define ( {
// Dependencies
], function (
// object with dependency
){
function yourModule ( ) {
// dependency objects received above
can used
}return yourModule;
});

It is possible for a module to have a few dependent modules but in general, an object will be returned by the end of the module. However, this outcome is not mandatory.

Comparison of RequireJS Dependency Management with Angular’s Dependency Injection:

The difference between RequireJS dependency management and Angular’s dependency management is one of the most frequently asked questions by Angular developers.

While RequireJS tries to load a module, it checks for every dependent module and proceeds to load them first. The objects of the loaded modules are cached and later, they get served when the same page requests once again. However, AngularJS possesses an injector that contains a list of names as well as corresponding objects. Upon creation of a component, an entry is added to the injector and the object gets served whenever it is referenced via the registered name.

Using AngularJS and RequireJS Together:

Most codes for simple applications contain various external dependencies, including:

  1. RequireJS
  2. Angular Resource
  3. jQuery
  4. AngularJS
  5. Angular UI’s ngGrid (Or any component library)
  6. Angular Route

All of the above-mentioned files need to be loaded directly on to the page in a specific order.

How to Define AngularJS Components In Terms of Requirejs Modules?
Almost every AngularJS component is made up of:

  • The Dependency injection
  • A function definition
  • Finally, registering with an Angular module

The first step involves defining a config block which does not depend on other blocks and is capable of returning the config function in the end. However, prior to loading the config module within another module, it is necessary to load every essential component required for the config block. The code below will be contained in config.js:

define ( [ ],function(){
function config($routeProvider) {
$routeProvider.when(‘/home’,{templateUrl:’
templates/home.html’,
controller:’ideasHomeController’})
.when(‘/details/:id’,{templateUrl:’templates/
ideaDetails.html’,
controller:’ideaDetailsController’})
.otherwise({redirectTo:’/home’});
}
config.$inject=[‘$routeProvider’];
return config;
});

The integral point to take note of is the way in which the dependency injection has been carried out in the code snippet above. $inject was used to get the dependencies injected while the config function defined above happens to be a plain JavaScript function. Prior to closing the module, config function must be returned so that it might be sent to the dependent module for use in the future.

The same approach may be followed for defining other kinds of Angular components also, since there is no component specific code contained in the files. The snippet below exhibits the definition of the controller:

define ( [ ], function() {
function ideasHomeController($-
scope, ideaDataSvc) {
$scope.ideaName = ‘Todo List';
$scope.gridOptions = {
data : ‘ideas’,
columnDefs: [
{ field:’name’, displayname:’Name’},
{ field:’technologies’,displaName:’
Technologies’},
{ field:’platform’,displaName:’Platforms’}
{ field:’status’,displaName:’Status’},
{ field:’devesNeeded’,displaName:’
Vacancies’},
{ field:’id’,displaName:’View Details’,
‘cellTemplate:'<a ng-href=”#/details/{{
row.getProperty(col.-
field)}}”>View Details</a>’}
],
enableColumnResize: true
};
ideasDataSvc.allIdeas( ).then(function(
result) {
$scope.ideas=result;
});
}
ideasHomeController.$inject=[‘$
scope’, ‘ideasDataSvc’];
return ideasHomeController;
});

The application’s Angular module is based on each of the modules that have been defined till this point. The file gains objects from all the other files and then hooks them in with an AngularJS module. It is possible that the file may or may not return something as the result of this file, but the Angular module may be referenced from anywhere with the help of angular.module( ). The following blocks of code define an Angular module:

define([‘app/config’,
‘app/ideasDataSvc’,
‘app/ideasHomeController’,
‘app/ideaDetailsController’],

function(config, ideasDataSvc, ideasHomeController,
ideaDetailsController) {
var app = angular.module(‘
ideasApp’, [‘ngRoute’,’ngResource’,
‘ngGrid’]);
app.config(config);
app.factory(‘ideasDataSvc’,ideas-
DataSvc);
app.controller(‘ideasHomeController’,
ideasHomeController);
app.controller(‘ideaDetailsController’,
ideaDetailsController);
});

No Angular application can be bootstrapped using the ng-app directive since the necessary files are loaded in asynchronous manner. The right approach here involves the use of manual bootstrapping and needs to be done in a special file named main.js. This requires the file defining the Angular module to be first loaded and the code is given below:

require {[‘app/ideasModule’],
function( ) {
angular.bootstrap(document,
[‘ideasApp’]);
}
);

Conclusion:

The process of managing dependencies tends to pose a challenge when the application size exceeds beyond a specific number of files. Libraries such as RequireJS make it simpler to define the dependency without having to worry about the loading order of the files. Dependency management involves becoming an essential part of the JavaScript applications. AngularJS 2.0 will receive the benefit of built-in support for AM

WHAT IS THE DIFFERENCE BETWEEN COMPILE AND LINK FUNCTION IN ANGULARJS ?

What is the difference between compile and link function in angularjs ?

In compile phase the angular parser starts parsing the DOM and whenever the parser encounters a directive it creates a function. These functions are termed as template or compiled functions. In this phase we do not have access to the $scope data. In the link phase the data i.e. ($scope) is attached to the template function and executed to get the final HTML output.

Compile – It works on template. It’s like adding a class element in to the DOM (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive.

Link – It works on instances. Usually used for registering DOM listeners (i.e., $watch expressions on the instance scope) as well as instance DOM manipulation. (i.e., manipulation of iElement = individual instance element).

HOW CAN I UPLOAD FILES ASYNCHRONOUSLY WITH JQUERY?

How can I upload files asynchronously with jQuery?

The “enctype” has to be mentioned in the AJAX call.

For example:

$(document).ready(function ( ) {
$(“#uploadbutton”).click(function ( ) {
var filename = $(“#file”).val(
);
$.ajax({
type: “POST”,
url: “addFile.do”,
enctype: ‘multipart/form-data’,
data: {
file: filename
},
success: function
( ) {
alert(“Data Uploaded: “);
}
});
});
});

DIFFERENCE BETWEEN BOWER AND NPM?

Difference between Bower and NPM?

The main difference between NPM and Bower is the approach for installing package dependencies. NPM installs dependencies for each package separately, and as a result makes a big package dependency tree(node_modules/grunt/node_modules/glob/node_modules/…), where there could be several versions of the same package. For client-side JavaScript this is unacceptable: you can’t add two different versions for jQuery or any other library to a page.

With Bower each package is installed once(jQuery will always be in the bower components/jquery folder, regardless of how many packages depend on it) and in the case of a dependency conflict, Bower simply won’t install the package incompatible with one that’s already installed.

HOW TO ACCESS PARENT SCOPE FROM WITH IN A CUSTOM DIRECTIVE *WITH OWN SCOPE* IN ANGULARJS?

How to access parent scope from within a custom directive *with own scope* in AngularJS?

The way a directive accesses its parent ($parent) scope depends on the type of scope the directive creates:

default (scope: false) – The directive does not create a new scope, so there is no inheritance here. The directive’s scope is the same scope as the parent/container.

scope: true – The directive creates a new child scope that prototypically inherits from the parent scope

scope: { x:’=foo’ } – The directive creates a new isolate/isolated scope. It does not prototypically inherit the parent scope. You can still access the parent scope using $parent, but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the =, @, and & notation.

transclude: true – The directive creates a new “transcluded” child scope, which prototypically inherits from the parent scope. The $parent property of each scope references the same parent scope.

Explain the same-origin policy with regards to JavaScript?

Explain the same-origin policy with regards to JavaScript?

The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin. Same-origin Policy is used as a means to prevent some of the Cross-site Request Forgery attacks.

The “origin” is the same if three things are the same: the protocol (http vs. https), the domain (subdomain.yoursite.com vs. yoursite.com vs. google.com), and the port (: 80 vs.: 4567). Using JS, we would be able to fetch resources (typically data like text,html,json,etc) using JSONP where we create a script tag dynamically with src attr pointing to the end source. Insert the script tag into the head section of the page. This will force the browser to fetch the end source similar to how it fetches any other JS or image via http.

PARALLAX SCROLLING WEBSITES AND SEO

PARALLAX SCROLLING WEBSITES AND SEO

Originally created for the gaming industry, parallax scrolling is basically a scrolling technique in computer graphics, where a background image moves in along with a foreground images, but at a slower rate. This kind of “special effects” technique creates an illusion of depth for a website.

Parallax scrolling is a pretty complicated design technique and you might want to keep the below mentioned points in mind.

  • Start with creating an SEO architecture, eventually moving on to implementation of your design.
  • Parallax Scrolling is really unsuitable for mobile websites or their mobile-friendly versions because it makes websites noticeably heavy. So, if your main site runs parallax scrolling, it is best to remove it from your mobile website since it will in invoke a tedious user-experience.

As a web developer, one should be aware that parallax scrolling can cause multiple SEO issues because it adds a lot of weight to a website, and no search engine wants to deal with a content heavy website, including Google. Again, it is recommended that one ascertain as to whether they really want or need parallax scrolling effects on their website.

This is because people are averse to change, and if you have a website that has been running for a long time and has high-traffic inflow, it’s best to keep track on how the users or visitors are reacting to the changes on the website.

Does Parallax Really Affect SEO?

To put all your doubts to rest, yes. If not implemented properly, parallax scrolling can seriously affect your SEO rankings. It is common knowledge that search engines search for and identify websites that are rich in content and functionality.

Coincidentally, search engines also loathe heavy website, putting web developers in a really tight spot. It is, however, useful to note that a parallax-enabled website is typically just a single or one-page website. You also know that you aren’t allowed to have multiple H1 headers or meta-descriptions for a website that has all of its content crammed into a single page, no matter how convenient it is for you.

Challenges of Parallax Scrolling:

So, let’s see what parallax scrolling actually does for your SEO intentions.

Parallax Design For SEO

1). Loading Time

Parallax-enabled websites have much longer load times than standard websites. And nothing is more annoying than a website that takes forever to load. In fact, statistics have revealed that users will switch websites if the load time exceeds 5 seconds, five seconds! Which means you only have 5 seconds to retain the interest of a potential customer.

2). Measuring User Engagement

For a website that employs parallax scrolling, it is very difficult and in some cases, virtually impossible, to measure the level of user engagement using Google Analytics. This is because Google Analytics employs a JavaScript tracking code, which it uses to obtain user engagement calculations. Plus, it is impossible to figure out where most of the user traffic is headed, on a site that hosts just a single page.

3. Not Always Browser-Friendly

It might be possible that a parallax page does not work properly across all Web browsers. A page can run properly in Firefox but fail to do so in Google Chrome. The same can happen in the case of Internet Explorer and Safari. It might require extensive testing to make sure that everything works accurately across all web browsers.

4. Not Mobile or SEO-Friendly

The biggest risk of running a parallax site may be its inability to run properly on mobile web devices. And with the ever-increasing popularity of mobile smartphones and tablets, non-mobile user friendly websites will definitely be a burden on their business. Another peculiar issue with enabling parallax scrolling is the difficulty for developers to optimize the site for specific keywords. This is because it is difficult to optimize for multiple keywords on a single page of web content, compared to that of a multiple-page website.

5. How to handle Parallax Scrolling and SEO?

Irrespective of how complicated a technique parallax scrolling may be, if you really want the parallax effect on your site, there are a few structural ideas that you can use to run your website with parallax scrolling while also keeping it search engine optimized.

A solid start would be to assign all internal links to different sections of the parallax website, which would really help the search engines index page content.

Another point you should consider is that these navigation functions can also be used for internal linking at the same time. This ensures seamless accessibility to the webpage, allows you to use the parallax effect, and use multiple pages simultaneously. By doing this, you will effectively have multiple URLs while also performing keyword-
specific optimization on them. It’s recommended that you use tools like Ajax and the navigation functions to change the URL. This will improve the user experience since they will be automatically redirected down to the webpage to the relevant post with a special URL.

Finally, try starting your own blog and keep updating it frequently. This will not only impress your guests by keeping the parallax effect running smooth on your site, but the blog you just created will also increase the flow of traffic to your site.

What’s this Typescript all About?

What’s this Typescript all About?

If you’re a Java programmer, you’ve probably heard of Typescript. But, what exactly is TypeScript?

Most web JavaScript developers will tell you that it’s a programming language that is strictly a superset of JavaScript. It provides JavaScript users with the added advantage of optional static typing and class-based object-oriented programming.

It is basically a compiled version of native JavaScript that runs without the support of a dedicated runtime library. It is designed and developed by Microsoft.

Overview

With the introduction of an optional typing system, TypeScript attempts to incorporate the advantages of a statically typed language into the dynamic world of JavaScript. Some of these benefits will include:

Type Script

  1. Accuracy with Type Checkers: Getting a platform that makes it easier for developers to create an accurate and predictable code that will eliminate common errors such as typos or incorrect value-type assumptions. Such errors are detected during the compile stage by type checkers.
  2. Seamless IDE Integration: With the information of types, an IDE can become more productive by providing useful features such auto-complete. It is open source, but you only get the clever Intellisense as you type if you use Microsoft’s Visual Studio.
  3. It is now possible to perform code refactoring operations like renaming functions or variables automatically and safely.

TypeScript vs JavaScript
Type Script is JavaScript with high level language features

TypeScript vs JavaScript
Classes

In relation to its structuring mechanism, TypeScript introduces the concept of a class-based object-oriented programming, making it much easier to structure code into classes, create a class hierarchy and manage the visibility of data throughout a system.

But in the JavaScript code, private members are publicly accessible. However, it is possible to hide methods and variables within JavaScript by placing them within a constructor function and making them accessible to the class internals through a closure.

Modules

TypeScript uses the concept of internal and external modules.

In the case of JavaScript, every variable/- function that isn’t defined in a function is created in a global scope. Variables defined without a “var” keyword will also be created. Cluttering the global namespace will cause naming conflicts. If this happens, variables or functions in the global scope will override existing ones with the same name and can create some untraceable errors.

TypeScript’s internal modules follow the same structure as namespaces as they allow defining of symbols like variables classes and the global scope. External modules are how TypeScript defines asynchronous loaded modules for either node.js or require.js module-loadingsystems.TypeScript also employs the use of a module to declare the application program interfaces that third-party libraries expose.

TypeScript Benefits

Here are some benefits that make Type- Script a prominent language:

  • A platform for safe and automatic refactoring.
  • High-visibility APIs and type declaration code contracts.
  • Easy error detection during compilation.
  • Class-based object orientation, with private members and an interface module support.
  • Easy interoperability of JavaScript code.
  • It allows you to convert any JavaScript code into a valid TypeScript code.
  • There is low or no risk in trying Type- Script since it can be removed as easily as it was installed.

The best part about TypeScript is that it allows you to begin with a JavaScript code and eventually add type annotations.

TypeScript Cons

Although TypeScript comes with loads of features and advantages, TypeScript also has its fair share of cons and limitations. So here are a few drawbacks of Type- Script compared to JavaScript:

      • To obtain the most out of TypeScript, developers are required to employ the use the type annotations at every point of their code, making such a dynamic language seem tedious and cumbersome. So, you’re going to have to devote plenitude of focus and effort while writing a strongly-typed JavaScript code.
    • Although the TypeScript system is way more flexible than what one typically finds among mainstream languages, it is still nowhere as flexible as the JavaScript language itself. In fact, JavaScript extends itself to a strong deal for TypeScript since it imposes a strongly-typed language system to make it easier to use with JavaScript, which is intrinsically dynamic.
  • Not all JavaScript patterns are 100% compatible with TypeScript. In fact, many commonly used JavaScript patterns can be difficult or impossible to use in Typescript. And although developers are working to create a smoother integration, it will take a couple of years to reach that point.

Why to use TypeScript:

Transparency:

TypeScript is a language that generates plain JavaScript files. The code produced follows all the JavaScript rules (the “good parts”) and thus is clean and modular (one file per class). You can export namespaces (modules) and to be honest most of the time the produced JavaScript is fairly the same as what we can do.

Developer Reach:

Furthermore, we can reach more users who can be afraid by JavaScript. Type-Script is for instance a good way for C#, Java and all strong typed languages developers to start developing for the web.

It technically boils down to its usage, for example, using TypeScript is much more advantageous for medium-large scale projects, but might not make as much sense for smaller projects.

Example:

As an example, here’s some Typescript (you can play with this in the Typescript Playground) and the Javascript code that it would produce.

Notice how the Typescript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

typescript vs javascript

It is by no means an improved version of JavaScript, nor a complete replacement for the same. In fact, in order to use and make the most out of TypeScript, a developer or development team will need to be fairly well-versed with TypeScript as well as JavaScript.