Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone js cannot return a value in events on

guys, I'm new to backboneJs, and I tried to write a basic program to return a value in events.on like below, but it 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 give me some ideals, thanks a lot.

like image 661
Marven Avatar asked Jun 07 '13 07:06

Marven


2 Answers

Backbone.Events are not created to return values, but as notification mechanism on objects. Return values of registered callbacks is ignored and actual object on which event was triggered is returned (that is why sum don't contain 4).

If you really need to extract something from event, you can restructure your code like this:

$(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);
});
like image 195
Marian Polacek Avatar answered Nov 15 '22 10:11

Marian Polacek


I come up with another solution about this question as 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);
});
like image 28
Marven Avatar answered Nov 15 '22 10:11

Marven