About the usage of jQuery bind function
I have a problem about the usage of bind function. Here is the example:
- // Parent class
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);
}
};
// Child class
function Button(width, height, label) {
// "super" constructor 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 base "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);
});
The upper code snippet is from the book [You Don’t Know JS: this & Object Prototypes], and the problem is the code :
- this.$elem.click(this.onClick.bind(this));
And the codes is put on https://jsfiddle.net/abramhum/k0btuvuz/ . The upper code can bind the Button.prototype.onClick to this.$elem, but I didn't know exactly how it works, and furthermore, since bind is depreciated and replaced by on, so, if I hope to use on to replace it, how to do that. Thanks a lot.