How to make an events base class in javascript? -


i trying make events class little canvas library making!

this have far,

function events() {  };  events.prototype.addevents = function() {      this.mousemove = false;     this.onmousemove = function() {          if (this.mousemove) {             this.mousemove();         }     };     this.mousedown = false;     this.onmousedown = function() {          if (this.mousedown) {             this.mousedown();         }     };     this.mouseup = false;     this.onmouseup = function() {          if(this.mouseup) {             this.mouseup();         }     };     this.click = false;     this.onclick = function() {          if (this.click) {             this.click();         }     };     this.on = function(type, callback) {      };  }; 

what cannot add other objects want assign events on. example object simple rectangle has draw method.

function rect() {      this.draw = function(context) {          // code     }; };  // how can add events prototype properties rect? have tried... // rect.prototype = new object.create(events.prototype); // rect.prototype = object.create(new events.prototype); 

i want events prototype give of it's properties object want have events on?

thank , hope made sense!!

so if i'm not mistaken want prototype of rect() inherit method addevent() prototype of events().

you don't use new when using object.create, new object.create(events.prototype) wrong. this:

rect.prototype = object.create(events.prototype); 

but then, object.create not supported on internet explorer 8 , below, maybe you'd rather use function:

function inherit(children, parent) {     var f = function() {};     f.prototype = parent.prototype;     children.prototype = new f();     children.prototype.constructor = children; }; 

there several patterns inheritance in javascript, 1 of them. if want learn others take @ stoyan stefanov's book javascript patterns, in case, 1 going job.

as can see, uses temporary function f() link between children , parent. have done children.prototype = parent.prototype, if @ point change in children.prototype, going changing parent.prototype in fact - don't want that.

we don't want this: rect.prototype = new events(). link rect.prototype event's prototype, if did that, declared in events keyword this going added rect - don't want happen. example, if events included this.whatever = 'value', whatever added rect.prototype.

so call described inherit function , pass 2 functions arguments, in way:

inherit(rect, events); 

and rect.prototype, then, going inherit methods of event's prototype.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -