Yesterday we were having a discussion about how we can extend Backbone.js so that we can have a separate controller with action methods the way we have in ASP.NET MVC rather putting the callbacks to be executed based on route matching in the Backbone.Router.One point which I mentioned casually is , “Javascript” does not sophisticated reflection like C# so that we can build a Router/Action Selector/Action Invoker/Controller sort of a pipeline.Later I thought that was very casual statement and not a very correct one.The kind of language Javascript is we do not need that kind of reflection and Javascript offers various ways to dynamically invoke functions.In this post we will explore different mechanisms of invoking functions in Javascript. We will start with the following simple code.

image

Here the “execute” function calls “func” and the function “func” defined in T is executed. Now let’s try to tweak the function “execute” in such a way so that it will accept a object  and a function name as parameter and execute that function defined in that object.

image

Here we are using the “apply” function of Javascript which is available for any function object. The definition of apply is as shown below:

apply([thisObj[,argArray]]) where

  • thisObj is the object that will be used as "this" i.e. object on which the function will be invoked
  • argArray is the argument array used to pass argument values to the function which is invoked

obj[func]” retrieves the function object based on the function name from the hash of “obj” and then “apply” is invoked on that function object.

As a next step let’s modify our function to accept few parameters.

image

The parameters are passed using the array p.

There is another Javascript function “call” which can be invoked on any function object to bind a particular object to it. This is defined as:

call([thisObj[, arg1[, arg2[,  [, argN]]]]]) where

  • thisObj (optional) -   The object to be used as the current object on which the function is invoked
  • arg1, arg2, , argN (optional list) -  A list of arguments to be passed to the method.

The main difference with “apply” is in the way the parameters are handled, instead of a parameter array it accepts individual parameters.This makes it rigid compared to “apply”.

The following code shows the use of call.

image

If you are using Underscore.js this can be achieved more easily with _.bind function.

_.bind(function, object, *arguments) where

  • function  is the function object which needs to be invoked
  • object is the current object on which the function is invoked
  • *arguments are arguments values which the function expects

Our sample code is modified with _.bind

image

The _.bind function internally uses apply as shown below.

image

In this post we will discuss about the scope of a javascript variable and how “hoisting” works in javascript. Let’s start with a simple global variable definition.

image

In this code “a” is defined as a global variable and should be accessible to all the functions.So quite naturally the function “f” will print “global” i.e. value of the global variable “a” in the console.

In the code below, we have introduced a small change and added declaration of another variable named “a” in the function “f”.

image

Here the program will give precedence to the local variable “a” and will print “local” to the console. So far it’s quite intuitive.

image

Here we are trying to access the value of “a” first followed by the local variable declaration of same name and then again printing it’s value to the console. Most of us would expect to the following in the console.

global

local

It will print the following instead:

undefined
local

This happens because the way javascript handles variable declaration and initialization.It first scans the function and finds out all the variables and declares them on top but does not initialize them. Then when the code executes it provides the initialization value in the actual line where its defined. So when the first console.log statement executes it sees that there is a variable named “a” defined but not initialized so it will print “undefined”.

This is how variable hoisting (moving to the top) works in javascript where the declarations are only hoisted and not the initialization.

So this can lead to undesirable behavior and it is safe to declare the variable at the top of the function before its use.

In my last post, we have seen how to define models in Backbone.js and create instances of their objects.In this post we will see how we can set & get attribute values in Backbone.js model.Backbone.Model exposes two functions set and get to do so. The code snippet below shows the use of these functions.

image

The code below tries to access one non-existent attribute’s (“c” in this case) value which obviously will return undefined.

image

We can handle this situation in an elegant way using the has function. The has function returns true/false based on whether a property exists or not.

image

The attributes attribute and the toJSON function returns the dump of the attributes & the value in JSON format. The code below will print “Object { a=2, b=4, c=5}”.

image

The unset function removes a particular attribute from the object hash.

image

The clear function will clear the entire object hash removing all the attributes.

image

So now we have covered mostly all the Backbone.js functions related to attribute manipulation. However we can provide model specific functions for getting/setting attributes instead of directly using the get & set methods as shown below.

image

image

In the next post, we will move change listeners and tracking in the model.

The Backbone.js models are javascript objects which stores data for the application.In this post we will see how we can create and initialize these models by extending the Backbone.Model object. Let’s start with a very simple example as shown in the snippet below:

image

Here we have used the extend function of Backbone.Model to create the model definition and instantiate it. This is a simple object without any properties. We can create it with properties as shown below:

image

We will see the following in browser console.

Object t: {"a":1,"b":2}

Backbone.js also provides an option to set the default values for model properties by setting the default property in extend as shown below:

image

Here, while defining the model we are setting defaults values of “a” and “b” as 1 and 2. While creating the object we are overriding the default value of “a” with 3. We will see the following browser console.

Object t: {"a":3,"b":2}

Backbone.js also provides an option to write an initializer by exposing the initialize property in the extend.

image

Here we can see in the console,

Object is initialized.{"a":3,"b":2}

If we want further customization then we can override the constructor itself as shown below:

image

Here, we can see the following output in the console.

Object is created

Object t: undefined

Here we have used our constructor but the we can see that the object is not properly initialized.This is because we have not invoked the constructor for Backbone.Model from our own constructor.

image

In the above code, we have invoked the Backbone.Model constructor by using the apply function on it and the object is properly initialized as evident from console log.

Custom constructor called..
Object is initialized.{"a":3,"b":2}
Object t: {"a":3,"b":2}

So its evident that initialize, defaults etc. are all are invoked from constructor of Backbone.Model. The constructor property completely overrides the Backbone.Model default constructor, so unless we need some very special object creation logic it is advisable not to use this.

JavaScript & DOM Event Handlers

Posted: February 25, 2014 in Javascript
Tags: , ,

During end of last year we faced some serious browser memory leak issues in one of our projects.As we dug deep into the problem we found that event handlers were not detached from the HTML elements properly and somehow these objects were not removed from the memory even when not in use.So the memory consumption was gradually increasing as new HTML elements were added to the DOM after each AJAX call. Finally, we fixed the problem and the standards i.e. do’s and don’ts were updated as usual.This project used jQuery and all the focus went towards how to avoid this in jQuery without delving deep into why this happens in jQuery.I always find this library dependent understanding a very risky proposition particularly in areas where the underlying matter is so simple to understand.

The most simple way to attach an event with a HTML element is as shown below:

evt1

The basic problem with this approach is mixing of HTML & javascript code going against the concept “unobtrusive javascript”. The other way of doing this by assigning a function to the event as shown below:

evt2

This approach solves the problem mentioned above. But both these approaches suffers from the drawback that there is no way to detach the event handler if required.The DOM Level 2 Event model provides the following functions using which it can be achieved:

  • target.addEventListener(type, listener[, useCapture])
    • type – event type
    • listener – function which will be triggered
    • useCapture – true/false indicating whether the event will be captured or not.
  • target.removeEventListener(type, listener[, useCapture])
    • type – event type
    • listener – function which will be triggered
    • useCapture – true/false indicating whether the event will be captured or not.

However in IE 5-10 these functions are named as attachEvent & detachEvent and IE 11 onwards it’s the standard set of functions as mentioned above.

Note, that to remove the handler also we need reference to the handler that we want to remove.Now lets try to develop to wrapper functions in order to add & remove events from any HTML element.

The following function attaches a handler to a HTML element and stores the reference of that handler in a cache.

image

This cache store is used to obtain the reference back when the handler is removed as shown below:

image

So in order attach & detach events we need to call them in pair. Since we need reference of the handler we just can’t use removeEventListener without having that reference.

jQuery follows quite similar coding style, it stores the event handlers in an internal variable $.cache. The reference is added to the cache when we use on/bind function and removed from the cache when we use off/unbind. So it’s always a good practice to use them in pair, otherwise a reference will remain stored in $.cache leading to memory issues.

ASP.NET 4.5 has introduced model binding and strongly typed templates for ASP.NET server controls.This simplifies the way a plain .NET object can be bound as a datasource of a server control like a GridView.Let’s get started off with a simple example of how model binding works.

Read the rest of this entry »

Singleton is the most widely known Design Pattern. Singleton makes sure that one only one instance of a class is created and the same instance is used by other programs and classes.An implementation of a Singleton class is shown below:

Read the rest of this entry »