Search code examples
javascriptbackbone.jsbackbone-events

What is the advantage of custom events in backbone?


I understand how custom events work in Backbone and how to trigger them, but I'm having trouble understanding when exactly to use them and what purpose they serve over just calling the function directly.

e.g.

var MyView = Backbone.View.extend({
    tagName: 'div',
    className: 'myview',

    initialize: function() {
        this.model.on("mycustomevent", this.doSomething, this);
    },

    doSomething: function() { 
         console.log('you triggered a custom event');
    }

});

If I am not mistaken, The doSomething method can be called by using this.model.trigger("mycustomevent") within other methods, but can be also called directly with this.doSomething()

Outside the view, it can be called similarly with

var myview = new MyView({model:somemodel});

myview.model.trigger("customevent");

myview.doSomething();

What I am confused about is why not forgo the the custom event and just call the method directly when you need it? Any example uses would be greatly appreciated!


Solution

  • You might want to add multiple handlers in different places in the code, f.ex:

    this.model.on("mycustomevent", this.doSomething, this);
    
    // ... and somewhere else you add an anonymous function
    this.model.on("mycustomevent", function() {
        console.log('do something');
    });
    

    Then when you trigger the event, it will execute all handlers. You can also use off to unbind/manage individual or multiple handlers.

    If you are asking about a generic explanation of the event pattern (also called observer pattern, publish/subscribe, etc...), you should probably look for a more in-depth article or book.