Jun 19, 2013

Simple reusable javascript object - basics

You need to create javascript to handle multiple instances of same type of functionality with ability to input standardized arguments.
We need to model Javascript object. Javascript does not support objects in OOP sense and this creates a lot of confusion. On top of it its dynamic language. Comparing it to .NET classes where mostly you deal with static members of class is not possible.
So here is example of simple Javascript object to implement creating and configuring simplest div container.
I'm using JQuery.

Declaring:
counterPanel = function (pnlId, argsParam) {
    var args = $.extend({
        title: "title",
        color: "rgb(255,250,250)",
        execute: null
        },argsParam
        );
    this.Show = function Show() {
         
        if (!DoesContainerExists(pnlId)) {      
            $('#countersContainer').append('<div id="'+pnlId+'"><h1 style="color:'+args.color+'">'+args.title+'</h1></div>');
        }
       
    }
    this.Hide = function Hide() {
        if (DoesContainerExists(pnlId)) {
            $('div#' + pnlId).Hide();
        }
    }
    if (typeof(args.execute) == 'function') args.execute();
    function DoesContainerExists(pnlId) {
        return ($('#countersContainer div#' + pnlId + ':First').attr('id') != undefined);
    }
}
Instancing with various input params including function injection.

var dlgFirst = new counterPanel("dlgFirst", {title:"something special", color:"rgb(0,0,100)"});
        dlgFirst.Show();
        var dlgSecond = new counterPanel("dlgSecond", { title: "special", color: "rgb(110,0,100)", execute: function () { alert('2');} });
        dlgSecond.Show();

1 comment:

  1. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. 经济代写

    ReplyDelete