Bind registers the provided handler to the current hooks queue. If handler.Id is empty it is updated with autogenerated value. If a handler from the current hook list has Id matching handler.Id then the old handler is replaced with the new one.
(handler *Handler[T])
| 63 | // If a handler from the current hook list has Id matching handler.Id |
| 64 | // then the old handler is replaced with the new one. |
| 65 | func (h *Hook[T]) Bind(handler *Handler[T]) string { |
| 66 | h.mu.Lock() |
| 67 | defer h.mu.Unlock() |
| 68 | |
| 69 | var exists bool |
| 70 | |
| 71 | if handler.Id == "" { |
| 72 | handler.Id = generateHookId() |
| 73 | |
| 74 | // ensure that it doesn't exist |
| 75 | DUPLICATE_CHECK: |
| 76 | for _, existing := range h.handlers { |
| 77 | if existing.Id == handler.Id { |
| 78 | handler.Id = generateHookId() |
| 79 | goto DUPLICATE_CHECK |
| 80 | } |
| 81 | } |
| 82 | } else { |
| 83 | // replace existing |
| 84 | for i, existing := range h.handlers { |
| 85 | if existing.Id == handler.Id { |
| 86 | h.handlers[i] = handler |
| 87 | exists = true |
| 88 | break |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // append new |
| 94 | if !exists { |
| 95 | h.handlers = append(h.handlers, handler) |
| 96 | } |
| 97 | |
| 98 | // sort handlers by Priority, preserving the original order of equal items |
| 99 | sort.SliceStable(h.handlers, func(i, j int) bool { |
| 100 | return h.handlers[i].Priority < h.handlers[j].Priority |
| 101 | }) |
| 102 | |
| 103 | return handler.Id |
| 104 | } |
| 105 | |
| 106 | // BindFunc is similar to Bind but registers a new handler from just the provided function. |
| 107 | // |