API · Observable

riot.observable(el)

Adds Observer support for the given object el or if the argument is empty a new observable instance is created and returned. After this the object is able to trigger and listen to events. For example:

function Car() {

  // Make Car instances observable
  riot.observable(this)

  // listen to 'start' event
  this.on('start', function() {
    // engine started
  })

}

// make a new Car instance
var car = new Car()

// trigger 'start' event
car.trigger('start')

@returns the given object el or a new observable instance

el.on(events, callback)

Listen to the given event and execute the callback each time an event is triggered.

// listen to single event
el.on('start', function(args) {

})

// listen all the events of this observable
el.on('*', function(event, param1, param2) {
  // event will be the name of any event triggered
  // do something with the parameters
})

@returns el

el.one(event, callback)

Listen to the given event and execute the callback at most once

// run the function once, even if 'start' is triggered multiple times
el.one('start', function() {

})

@returns el

el.off(events)

Removes the given event listeners.

el.off('start')

@returns el

el.off(events, fn)

Removes the given callback listening to the event

function doIt() {
  console.log('starting or ending')
}

el.on('start', doIt)

// remove a specific listener
el.off('start', doIt)

@returns el

el.off(‘*’)

Removes all listeners from all event types.

@returns el

el.off(‘*’, fn)

Removes the specific callback function called on all the events

@returns el

el.trigger(events)

Execute all callback functions that listen to the given event.

el.trigger('start')
el.trigger('render')

@returns el

el.trigger(event, arg1 … argN)

Execute all callback functions that listen to the given event. Any number of extra parameters can be provided for the listeners.

// listen to 'start' event and expect extra arguments
el.on('start', function(engine_details, is_rainy_day) {

})

// trigger start event with extra parameters
el.trigger('start', { fuel: 89 }, true)

@returns el