A javascript object that implements the observer or pub/sub pattern.
It implements the observer pattern or a publish-subscribe system based on subjects and functions registered under them.
- The registration signature is:
register(func, subject, context)
.
If'subject'
is ommited then it's'g3'
, if'context'
is omitted then function is called as usual otherwise it changes context and runs under the new one. A function can register under many subjects. It can be chained. - The unregister signature is:
unregister(func, subject, context)
.
It breaks the chain and returns the number of unregistered functions. - Our functions signature is:
function ([subject, arg1, arg2, ...])
.
When a message is fired for a specific subject then, all registered functions are called and an array is passed to them constructed from the arguments of the notify function. notify(subject)
It breaks the chain and returns the number of the functions it calls. If there are no registered functions under this subject then, it returns false.get(subject)
breaks the chain and returns the array of objects[{function, context}, ...]
under a subject or the object of all subjects if subject is null:{length: n, subject1: [{function, context}, ...], ...}
.- reset()
converts the object of all subjects to:{length: 0}
. It can be chained.
This version uses publisher or observable to push notification messages to observers in contrast of a pull system where every observer queries the observable.
It will become part of our javascript plugin extension mechanism using object mixin techniques and allowing the user to extend the behaviour of any (jQuery, whatever) plugin with the help of a class library.
The g3.evaluator
is used to test functioning behaviour of this object along with jasmine v.2.0.
my source files (g3), necessary libraries (jquery) and my tests folder (tests): client : |-jquery : : |-g3 : |- <g3MyClass.js> : : |-tests : |-jasmine-standalone-2.0.0 | |-lib | |-spec : : |-g3 : |- <g3MyClass-SpecRunner.html> |- <g3MyClass-Spec.js> |- <g3MyClass-SpecHelper.js> |- g3evaluator.css |- g3evaluator.js |- g3evaluator.html (rename this file to test-g3MyClass.html) |- <test-g3MyClass.html> :
There are two g3
folders: the one contains the actual code and the other under tests
contains the test files.
Have fun!