Events

Classes

Game <- setRefClass("Game",
  fields = list(name = "character",
                callbacks = "list"),
  methods = list(
    start = function() {
      for (callback in callbacks) {
        callback(name)
      }
    }
  )
)

Statistic <- setRefClass("Statistic",
  fields = list(starts_count = "numeric",
                last_game = "character"),
  methods = list(
    game_started = function(game_name) {
      last_game <<- game_name
      starts_count <<- starts_count + 1
    }
  )
)

statistic <- Statistic$new(starts_count = 0)
heroes <- Game$new(name = "Heroes")
doom <- Game$new(name = "Doom")

# Subscribe to events: add a handler
handler <- statistic$game_started
heroes$callbacks <- c(heroes$callbacks, handler)
doom$callbacks <- c(doom$callbacks, handler)

doom$start()
heroes$start()
# statistic$last_game = Heroes
# statistic$starts_count = 2

cat("statistic$last_game =",
    statistic$last_game, "\n")
cat("statistic$starts_count =",
    statistic$starts_count, "\n")