I started my first Prism plugin. Prism uses hooks or in other software often called events to get simple plugin architecture. It is often a good idea to get an overview about all available hooks that Prism runs without any plugins. I will show in this post a small list with some explainations.
Hooks are in Prism the same as in other software, some call hooks also events. Prism run
s the hooks and
our plugin has the possibility to add
a callback on a hook.
Here a small run
example with the very popular hook complete
.
_.hooks.run('complete', env);
The underscore _
variable is in this case Prism itself and the env
variable looks
something like that.
var env = {
element: element,
language: language,
grammar: grammar,
code: code
};
The env
variable will be injected into our callback function if we add
on a hook.
Here a small example of a minimal plugin that add
s a callback on the hook complete
.
(function(){
if (typeof self === 'undefined' || !self.Prism || !self.document || !document.querySelector) {
return;
}
Prism.hooks.add('complete', function(env) {
console.log("Hello Prism");
});
})();
As mentioned above it can be very helpful to get an overview about all hooks that are availabe. I often put just a
console.log
into the hooks.run
function of prism.js
and refresh the browser
window.
hooks: {
all: {},
add: function (name, callback) {
var hooks = _.hooks.all;
hooks[name] = hooks[name] || [];
hooks[name].push(callback);
},
run: function (name, env) {
console.log(name);
var callbacks = _.hooks.all[name];
if (!callbacks || !callbacks.length) {
return;
}
for (var i=0, callback; callback = callbacks[i++];) {
callback(env);
}
}
}
Here the default list of Prism hooks with the object variables of the env
variable.
name | env |
---|---|
before-highlightall | callback, selector |
before-sanity-check | element, language, grammar, code |
before-highlight | element, language, grammar, code |
wrap | type, content ,tag, classes, attributes, language, parent |
before-insert | element, language, grammar, code, highlightedCode |
after-highlight | element, language, grammar, code, highlightedCode |
complete | element, language, grammar, code, highlightedCode |