javascriptbackbone.jseventtriggersaiku

Trigger event in Backbone.js and Saiku


I'm new to backbone. I have been looking it has been used in Saiku. I came across the below line.

Saiku.session.trigger('workspace:new', { workspace: this });

Is 'workspace:new' an event? How does backbone trigger recognize it as an event?


Solution

  • Short answer: yes, workspace:new is an event.

    Backbone has several built-in events that you can listen for. But you can also trigger custom events, as this code does. The event is identified by only a string (in this case, "workspace:new"). When you call trigger on an object that inherits from Backbone's Event Module, that event "happens." As a second parameter to trigger, you can pass some data about the event, anything you want accessible from the event handler function.

    Then, usually somewhere else, there will be code waiting for that event to happen. That is set up by calling the .on or .listenTo methods.

    Here's a basic example: (See it in action on JSBin)

    var model = new Backbone.Model();
    
    model.on('my-event', function (data) {
        console.log("my-event happened!");
        console.log(data);
    });
    
    
    model.trigger('my-event');
    model.trigger('my-event', 'some-data');
    model.trigger('my-event', { anything: 'works' });