javascriptjqueryjquery-eventscanjscanjs-control

Set up a global listener/controller for events triggered on document with CanJS


Probably not the common use case, but I have several custom events being fired on document, and the application listens for them. Example: http://jsbin.com/uradod/3/edit

How can I convert this to be CanJS controller? I was of something similar to this: http://jsbin.com/uradod/6/edit. Is it possible? If so, how?


Solution

  • You can listen to non standard events by adding a whitespace before the event name. For some reason it didn't work on JSBin but here is a Fiddle: http://jsfiddle.net/BT95c/

    can.Control('Events',
    /** @Static */
    {},{
        " sampleEvent" : function(el, ev, data)
        {
            $('body').html('Controller: ' + data.text);
        }
    });
    
    var events = new Events(document);
    
    $(document).trigger("sampleEvent", {text:"Event trigger"});