Saturday, March 12, 2016

Create a widget using javascript

Javascript code

function Widget(width,height){
    this.width=width||50;
    this.height=height||50;
    this.$elem=null;
}

Widget.prototype.render=function($where){
    if(this.$elem){
        this.$elem.css({
            width:this.width+"px",
            height:this.height+"px"
        }).appendTo($where);
    }
};

function Button(width,height,label){
    Widget.call(this,width,height);
    this.label=label;
    this.$elem=$("<button>").text(this.label);
}

Button.prototype.render=function($where){
    Widget.prototype.render.call(this,$where);
    this.$elem.bind("click",this.onClick.bind(this));
};

Button.prototype.onClick=function(event){
    //We used this here because we use the hard binding in render function
    console.log("Button '"+ this.label+"' Was clicked");
};

$(document).ready(function(){
    var $body=$(document.body);
    var btn1=new Button(100,50,'Hola');
    var btn2= new Button(200,50,'Hello');

    btn1.render($body);
    btn2.render($body);
});


Equivalent javascript code

var Widget ={
    init: function(width,height){
        this.width=width||50;
        this.height=height||50;
        this.$elem=null;
    },
    insert: function($where){
        if(this.$elem){
            this.$elem.css({
                width:this.width+"px",
                height:this.height+"px"
            }).appendTo($where);
        }
    }
};

var Button =Object.create(Widget);

Button.setup=function(width,height,label){
    this.init(width,height);
    this.label=label||"Default";
    this.$elem=$("<button>").text(this.label);
};

Button.build=function($where){
    this.insert($where);
    this.$elem.click(this.onClick.bind(this));
};

Button.onClick=function(){
    console.log("Button '"+ this.label+"' clicked!");
};

$(document).ready( function(){
    var $body=$(document.body);

    var btn1=Object.create(Button);
    btn1.setup(125,30,"Hello");

    var btn2=Object.create(Button);
    btn2.setup(150,60,"Hola");

    btn1.build($body);
    btn2.build($body);

});


Html code

<html>

<head>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="widget.js"></script>
</head>

<body>

</body>


</html>



2 comments:

  1. Thank you for posting such a nice useful and impressive content.
    node js developer london

    ReplyDelete
  2. Excellent tips. Really useful stuff .Never had an idea about this, will look for more of such informative posts from your side... Good job...Keep it up
    seo services in UK
    web design development company in UK

    ReplyDelete