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.
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);
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With