godispatcher

package module
v0.0.0-...-5fc82ab Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2018 License: MIT Imports: 1 Imported by: 0

README

Build Status GoDoc Go Report Card

About the project

This is an experimental library. I tried to implement observer pattern in go without looking at existing solutions.

One can say that it's not "go way". We'll see. I want to implement couple of solutions and compare them.

How to use

See examples directory for more details.

package main

import (
	"errors"
	"fmt"
	"github.com/beono/godispatcher"
	"github.com/beono/godispatcher/examples/manager"
)

func validateUser(event *godispatcher.Event) error {
	if user, ok := event.Data.(*manager.User); ok {
		if user.Email == "" {
			return errors.New("email can't be empty")
		}
	}
	return nil
}

func main() {

	dispatcher := godispatcher.New()
	dispatcher.On(manager.UserUpdateBefore, validateUser)

	UserManager := manager.UserManager{
		Observer: dispatcher,
	}

	newUser := manager.User{
		ID:    0,
		Email: "",
	}

	fmt.Println(UserManager.Update(newUser)) // prints "email can't be empty"
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Dispatcher

type Dispatcher struct {
	// contains filtered or unexported fields
}

Dispatcher (a.k.a event emitter, dispatcher) stores listener and notifies them when an event emitted

func New

func New() Dispatcher

New returns new Dispatcher

func (Dispatcher) Emit

func (o Dispatcher) Emit(eventName string, data interface{}) error

Emit notifies listeners about the event

func (Dispatcher) On

func (o Dispatcher) On(event string, listener Listener)

On adds new listener. listener is a callback function that will be called when event emits

type Event

type Event struct {
	Name string
	Data interface{}
}

Event is used to transfer event-related data. It is passed to listeners when Emit() is called

type Listener

type Listener func(event *Event) error

Listener is a type for listeners

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL