IIFE

IIFE stands for: Immediately-Invoked Function Expression
It is a self-executing anonimous function like this:

(function($){
    $.fn.myplugin = funnction(options) {
        var settings = {};
        $.extend(settings, this.myPlugin.defaults, options);
        return this;
    };

    $.fn.myPlugin.defaults = {
        option1: 'option1',
        option2: 'option2',
        option3: 'option3'
    };
})(jQuery);

Another good example

// Create an anonymous function expression that gets invoked immediately,
// and assign its *return value* to a variable. This approach "cuts out the
// middleman" of the named `makeWhatever` function reference.
//
// As explained in the above "important note," even though parens are not
// required around this function expression, they should still be used as a
// matter of convention to help clarify that the variable is being set to
// the function's *result* and not the function itself.

var counter = (function(){
  var i = 0;

  return {
    get: function(){
      return i;
    },
    set: function( val ){
      i = val;
    },
    increment: function() {
      return ++i;
    }
  };
}());

// `counter` is an object with properties, which in this case happen to be
// methods.

counter.get(); // 0
counter.set( 3 );
counter.increment(); // 4
counter.increment(); // 5

counter.i; // undefined (`i` is not a property of the returned object)
i; // ReferenceError: i is not defined (it only exists inside the closure)

Source: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Passing Date parametere from Javascript to WCF

Having a service method that accepts two parameters will look like this:

[DataContract()]
public class ServiceRequest
{
[DataMember()]
Nullable<DateTime> DateTimeFrom {
get; set; }
[DataMember()]
Nullable<DateTime> DateTimeTo {
get; set; }
}

[ServiceContract()]
public interface IService
{
[WebInvoke(UriTemplate =
"getServiceCall", Method = "POST")]
ServResponse GetBusinessObjects(ServiceRequest filter);
}

Now, To start calling this method we need to construct a Json data representing the parameters.

      var fromDate = new Date(2013, 06, 18);
var toDate = new Date();

var datavar = {
DateTimeFrom: fromDate.toMSJSON(),
DateTimeTo: toDate.toMSJSON()
};
var parameters = JSON.stringify(datavar);

But, before calling the toMSJSON on date object we need to define it as follows:

// Let Date type be compatible for Microsoft WCF
Date.prototype.toMSJSON = function () {
/// <summary>Let Date type be compatible for Microsoft WCF.
</summary>

var date = ‘/Date(‘ + this.getTime()  + ‘-0000)/’;

};




Getting DateTime from WCF


// convert WCF date to Javascript
String.prototype.DateWCF = function () {
/// <summary>convert string into Date</summary>
var matches = this.match(//Date(([0-9]+)(?:.*))//);
if (matches)
return new Date(parseInt(matches[1]));
};

Notice that when you use a date in javascript it is representing your local date based on the settings on your systemn and browser. As a result you might pass different notation to WCF. For example, my broweser has an timezone offset of -120 minutes. So when I ask to convert 06/20/2013 02:10:04 I see 2013-06-20T00:10:04.000Z which is perfectly normal because that represents the same exact time as I meant on my browser. Thus WCF will get the correct date aswell.

Encapsulating an AJAX client control into a custom server control (Part 3)

The previous article was a step forward but it is still far from reusing as a server side control. What we will do in this part will make us possible to have a custom textbox control that makes al it takes to have this client-side functionality and we will be able to drag the ASP.NET control into our page.
To start with, we need a new server-side control library project that will compile as a dll and contains the server side code and embeds the client-side script. This project will have two files in it: the PassTextBox.cs which deals with the server-side TextBox and inherits from TextBox and implements the IScriptControl which makes it possible to embed the script code.
Notice in the code that the class needs to register the script with the ScriptManager which is accessible through its static method GetCurrent(Page). This is done in OnPreRender method.
In the previous article we had the css class names inside the javascript. In this example we will assign them through the controls properties. The GetScriptDescriptor method allows us to prototype our class where we define these properties.

namespace Panahy.Ajax
{
 
public class PassTextBox : TextBox, IScriptControl
  {
private ScriptManager sMgr;
public string WeakCssClass;
public string MediumCssClass;
public string StrongCssClass;
protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
 
ScriptControlDescriptor descriptor =
   
new ScriptControlDescriptor(“Panahy.Ajax.PassTextBox”, this.ClientID);

  descriptor.AddProperty(“weakCssClass”, this.WeakCssClass);
  descriptor.AddProperty(
“mediumCssClass”, this.MediumCssClass);
  descriptor.AddProperty(
“strongCssClass”, this.StrongCssClass);
  return new ScriptDescriptor[] { descriptor };
}

protected virtual IEnumerable<ScriptReference> GetScriptReferences()
{
 
ScriptReference reference = new ScriptReference();

  reference.Assembly = “Panahy.Ajax”;
  reference.Name =
“Panahy.Ajax.PassTextBox.js”;
 
return new ScriptReference[] { reference };
}

protected override void OnPreRender(EventArgs e)
{
 
if (!this.DesignMode)
  {
   
//test for the existence of a ScriptManager
   
sMgr = ScriptManager.GetCurrent(Page);

    if (sMgr == null)
      
throw new HttpException(“A ScriptManager control must exist on the page.”);
    sMgr.RegisterScriptControl(this);
  }
 
base.OnPreRender(e);
}

protected override void Render(HtmlTextWriter writer)
{
 
if (!this.DesignMode)
    sMgr.RegisterScriptDescriptors(
this);
  base.Render(writer);
}

IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
{
 
return GetScriptReferences();
}

IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
{
 
return GetScriptDescriptors();
}
}
}

The javascript file remains as before.
Now we can reuse the control in any project that refers to the dll.

<%@ Register Assembly=”Panahy.Ajax” Namespace=”Panahy.Ajax” TagPrefix=”panahyAjax” %>

<panahyAjax:PassTextBox ID=”textbox1″ runat=”server” width=”200″
   
TextMode=”Password” WeakCssClass=”weak” MediumCssClass=”medium”
    StrongCssClass
=”strong”></panahyAjax:PassTextBox>



Although this sample can be handy to use as a template for other server controls, the introduced functionality could be done by creating an AJAX Behavior for client controls, which is the topic for the next article.

Implementing Custom Classes for Microsoft AJAX Library (Part 2)

The previous article is demonstrates the use of custom class but it makes some assumption which is not best practice for developping pages.
In this article I will try to make this one step forward by taking the class names (that were hard coded in the javascript) out of the script and assign them in the page. I will also provide a initialization to assign the same functionality to any page element.
We start with the construction and pass the element that is using the class:

Panahy.Ajax.PassTextBox = function(element) {
    Panahy.Ajax.PassTextBox.initializeBase(
this, [element]);

    // initialize internal variables
   
this._weakCssClass = null;
    this._mediumCssClass = null;
    this._strongCssClass = null;
}
Next, I call the passwordStrengthClass method in a new event handler called _onKeyup which I will apply the css class to the element using get_element():

//define key press event
_onKeyup : function(e) {
    //get password text
    var pass = this.get_element().value;
    var strength = this.returnPasswordStrength(pass);
    switch (strength) {
      case “Weak”:
         this.get_element().className = this._weakCssClass;
         break;
      case “Medium”:
         this.get_element().className = this._mediumCssClass;
         break;
      case “Strong”:
         this.get_element().className = this._strongCssClass;
         break;
    }
},
Now, I need to tell the AJAX Library to assign the _onKeyup method to keyup event of the element. To do this, I create a delegate and add the handler as follows:

//initialize the UI control
initialize: function() {
   Panahy.Ajax.PassTextBox.callBaseMethod(
this, ‘initialize’);

  
this._onKeyupHandler = Function.createDelegate(this, this._onKeyup);
   $addHandlers(
this.get_element(), {‘keyup’ : this._onKeyup}, this);
},
By doing this, I have to remove the reference when cleaning up the things in the dispose method:

dispose: function() {
    $clearHandlers(
this.get_element());
    Panahy.Ajax.PassTextBox.callBaseMethod(
this, ‘dispose’);
},
It is almost done, except the definition of the get and set properties which can be done like this:

//define properties
get_weakCssClass: function() {
   return this._weakCssClass;
},
set_weakCssClass: function(value) {
   this._weakCssClass = value;
},
I need to do this for all three properties.
Now, I can use this in my page after referencing it in the ScriptManager.

<script language=”javascript” type=”text/javascript”>
  var app = Sys.Application;
  app.add_init(appInit);

  function appInit(sender, args) {
    $create(Panahy.Ajax.PassTextBox,
        { weakCssClass:
‘weak’, mediumCssClass: ‘medium’, strongCssClass: ‘strong’ },
        
null, null, $get(‘MainContent_TextBoxPassword’));
}
</script>
In this way, I don’t need to set anything on the textbox.
This is still not perfect, In the next article I will demonstrate how to put this in a custom ASP.NET Control.

Implementing Custom Classes for Microsoft AJAX Library (Part 1)

This article explainis the basic steps for impplementing your own javascript class and use it in a page.
First, you need to write a script that describes the class. This example simply provides a class that verifies the length of a word to see if it has enough length to be used as a password. The file name is PasswordStrengthComponent.js

/* When working with JavaScript files in the code editor, you can add a reference to the Microsoft AJAX Library. This will ensure that your coding includes IntelliSense for the library. This is similar to the using statement in C# and the Imports statement in Visual Basic. You embed this reference in a comment at the top of your .js file. The following shows an example.
*/
/// <reference name=”MicrosoftAjax.js”></reference>

// register your namespace
Type.registerNamespace(“Panahy.Ajax”);

//create constructor
Panahy.Ajax.PasswordStrengthComponent = function () {
    Panahy.Ajax.PasswordStrengthComponent.initializeBase(this);
}

//define class
Panahy.Ajax.PasswordStrengthComponent.prototype = {
    initialize: function () {
        //add custom initialization here
        Panahy.Ajax.PasswordStrengthComponent.callBaseMethod(this, ‘initialize’);
    },

    passwordStrengthClass: function (password) {
        var strPass = new String(password.toString());
        if (strPass.length &lt; 5) {
            return “Weak”;
        }
        else if (strPass.length &lt; 8) {
                return “Medium”;
        } else {
            return “Strong”;
        }
    },

    dispose: function () {
        //add custom dispose actions here
        Panahy.Ajax.PasswordStrengthComponent.callBaseMethod(this, ‘dispose’);
    }
}

//register class as a Sys.Component
Panahy.Ajax.PasswordStrengthComponent.registerClass(
    ‘Panahy.Ajax.PasswordStrengthComponent’, Sys.Component);

//notify script loaded
if (typeof (Sys) !== ‘undefined’) Sys.Application.notifyScriptLoaded();

Next, you reference this script file in your page within the ScriptManager:

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
    <Scripts>
        <asp:ScriptReference Path=”Scripts/PasswordStrengthComponent.js” />
    </Scripts>
</asp:ScriptManager>

From this point the script is available and can be used in thepage as in the following example:
<script language=”javascript” type=”text/javascript”>
    function _OnKeypress() {
        var checker = new Panahy.Ajax.PasswordStrengthComponent();
        var pass = document.getElementById(“MainContent_TextBoxPassword”).value;
        var strength = checker.passwordStrengthClass(pass);
         
        document.getElementById(
            “MainContent_TextBoxPassword”).setAttribute(“class”, strength);
    }
</script>
<asp:TextBox ID=”TextBoxPassword” runat=”server”
        TextMode=”Password” Width=”200″ onkeyup=”_OnKeypress()” CssClass=”Empty”></asp:TextBox>



Next part will take this subject one step forward.

Disabling the Browser Context Menu

Date: Monday, 18 Dec 2006 14:14
By Bret Taylor, December 3, 2006

You can disable the browser context menu for an element in your DOM with the following JavaScript recipe:

function disableContextMenu(element)
{
element.oncontextmenu = function()
{ return false; }
}

For example, to disable the context menu over a photo on your page, you could use:

disableContextMenu(document.getElementById("photo"));

Browsers like Firefox do not always allow web pages to disable the context menu (this option is a setting in Firefox), so this recipe will not work 100% of the time in all browsers.

See the example

JavaScript Debug Log

Date: Monday, 18 Dec 2006 14:08
By Bret Taylor, December 3, 2006

Even with the most advanced debugging tools, every program requires a little “printf debugging”: run your program, print out state as it executes, and visually verify that everything is working properly. Unfortunately, there is no built in console to print debug messages to in JavaScript, forcing many JavaScript programmers to revert to calling alert() in their code. alert is completely infeasible for a function that gets called a lot, as it halts execution until you click an OK button. This recipe creates a simple debug log window that does not halt execution:


function log(message) {
if (!log.window_ log.window_.closed) {
var win = window.open("", null, "width=400,height=200," +
"scrollbars=yes,resizable=yes,status=no," +
"location=no,menubar=no,toolbar=no");
if (!win) return;
var doc = win.document;
doc.write("<html><head><title>Debug Log</title></head>" +
"<body></body></html>");
doc.close();
log.window_ = win;
}
var logLine = log.window_.document.createElement("div");
logLine.appendChild(log.window_.document.createTextNode(message));
log.window_.document.body.appendChild(logLine);
}

To print log messages, you just call log() within your code:


for (var i = 0; i < 10; i++) {
log("This is log message #" + i);
}

When you push your code to production, you can just replace the definition of log with an empty function so your users will not see your debug messages.

See the example