I am facing problem in running below code which i have copied from the YDKJS book, will appreciate if someone can point how exactly should i run the code from the book.
HTML Code.
<html>
<head>
<title>Test Page.</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="bootstrap/js/bootstrap.js" ></script>
<script src="scripts/main.js"></script>
<!--<link rel="stylesheet" type="text/css" href="styles/css.txt"/>-->
<style>
</style>
</head>
<body>
</body>
</html>
JAVA SCRIPT CODE
function Widget(width,height){
this.width = width || 0;
this.height = height || 0;
this.$elem = null;
}
Widget.prototype.render = function($where){
if(this.$elem){
this.$elem.css({
width: this.width + "px",
height: this.height + "px"
}).appendTo( $where );
}
};
//child class
function Button(width,height,label) {
// "super" constructive call
Widget.call(this, width, height);
this.label = label || "Default";
this.elem = $( "<button>" ).text(this.label);
}
//make button inherit from widget
Button.Prototype = Object.create(Widget.prototype);
//override inherited render
Button.prototype.render = function($where){
//super call
Widget.prototype.render.call(this, $where);
//this.$elem.click( this.onClick.bind( this ) );
}
Button.prototype.onClick = function(evt){
console.log("Button '" + this.label + "' Clicked!");
}
$(document).ready(function(){
var $body = $(document.body);
var btn1 = new Button(125, 30, "Hello");
var btn2 = new Button(150, 40, "World!");
btn1.render($body);
btn2.render($body);
});
You have a couple of typos.
Around line 21:
this.elem
should be this.$elem
Around line 27:
Button.Prototype
should be Button.prototype
Yes its because of typos, one question though, what is the significane of using $ in code, It can work without $ right?
It’s just another character that you can use in variable names. When I store jQuery objects I often use variables with $
at the front (like in var $submit = $('.submit');
), just to make it immediately clear what’s stored in those variables.
So this code is using Jquery right? as when i replace $ from $(document), It fives error saying ready is not a function.
Also Is it necessary to set the this.$elem = null in function Widget?
The code would work the same without it, but IMO it’s probably better to leave it there because Widget.prototype.render
uses that same property (so when you inspect that method, you don’t ask where it magically comes from; it’s making the existence of this.$elem
more explicit so to speak)
Yes thanks a lot, Now I have understood this, I must say one of the most complex line from the code is in Button.Prototype.render function:
this.$elem.click( this.onClick.bind( this ) );