Backbone js cannot return value in events on

Guys, I'm new to backboneJs, and I tried to write a basic program to return the value in events.on, as shown below, but this does not work.

$(function(){ // object.on(event, callback, [context])Alias: bind var object = {}; _.extend(object, Backbone.Events); object.on('add',function(a,b){ return a + b; }); var sum = object.trigger('add',1,3); // not as I expected. alert(sum); }); 

I hope someone will give me some ideals, thanks a lot.

+6
source share
2 answers

Backbone.Events are not created to return values, but as a mechanism for notifying objects. The returned values โ€‹โ€‹of the registered callbacks are ignored and the actual object on which the event was triggered is returned (therefore, the sum does not contain 4).

If you really need to extract something from the event, you can rebuild your code as follows:

 $(function(){ // object.on(event, callback, [context])Alias: bind var object = {}; _.extend(object, Backbone.Events); // register variable outside of callback scope var sum; object.on('add',function(a,b){ // store result inside variable coming from outside sum = a + b; }); // trigger don't return anything, but sum variable will be filled object.trigger('add',1,3); // not as I expected. alert(sum); }); 
+4
source

I came up with a different solution on this, as shown below:

  $(function(){ // object.on(event, callback, [context])Alias: bind var object = {}; _.extend(object, Backbone.Events); // add a attribute 'sum' for the object, to hold the value. object.on('add',function(a,b){ return this.sum = a+b; }); var r = object.trigger('add',1,3); alert(r.sum); }); 
+1
source

Source: https://habr.com/ru/post/946750/


All Articles