Javascript - duplicate listeners if callback is defined in prototype and then bound -


basically, have implemented observable object , class (i.e. subscriber) has callback function in prototype.

in callback, want class's properties, therefore, has set correctly. here's example.

subscriber = function() {     this.pararma = 1; }  subscriber.prototype.onvaluechanged = function(value){     alert(this.parama + value); } 

in observable, listener has unique (i.e. same listener not allowed added subscriber list more once). below test.

var = observable(0); var b = new subscriber();  a.addlistener(b.onvaluechanged.bind(b)); a.addlistener(b.onvaluechanged.bind(b));  a(1); a(2); 

what expected see alert of 2 , 3 once instead saw alert of 2 , 3 twice due 1st b.onvaluechanged.bind(b) "identical" 2nd b.onvaluechanged.bind(b)

if add following code previous block of code:

var c = b.onvaluechanged.bind(b); var d = b.onvaluechanged.bind(b);  alert( c == d ); 

i popup saying "false"

so thinking put callbacks class instead of prototype:

i.e.

subscriber = function() {     this.pararma = 1;      this.onvaluechanbed = function(value){         alert(this.parama + value);     }.bind(this); } 

then in code use callback is:

var = observable(0); var b = new subscriber();  a.addlistener(b.onvaluechanged); a.addlistener(b.onvaluechanged); 

this solution seems ok every object callbacks have copy of callback functions (because using prototype should reduce memory consumption)


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

mysql - Pass value between different pages (form) with PHP -