Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active April 22, 2018 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/4dd72ebc62b2a40b9c6f75aeac582a99 to your computer and use it in GitHub Desktop.
Save Kcko/4dd72ebc62b2a40b9c6f75aeac582a99 to your computer and use it in GitHub Desktop.
What about using triggers? Does anyone know any drawback using them? The benefit is that all internal variables are accessible via the triggers, and the code is very simple.
See on jsfiddle.
Example usage
<div id="mydiv">This is the message container...</div>
<script>
var mp = $("#mydiv").messagePlugin();
// the plugin returns the element it is called on
mp.trigger("messagePlugin.saySomething", "hello");
// so defining the mp variable is not needed...
$("#mydiv").trigger("messagePlugin.repeatLastMessage");
</script>
jQuery.fn.messagePlugin = function() {
return this.each(function() {
var lastmessage,
$this = $(this);
$this.on('messagePlugin.saySomething', function(e, message) {
lastmessage = message;
saySomething(message);
});
$this.on('messagePlugin.repeatLastMessage', function(e) {
repeatLastMessage();
});
function saySomething(message) {
$this.html("<p>" + message + "</p>");
}
function repeatLastMessage() {
$this.append('<p>Last message was: ' + lastmessage + '</p>');
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment