Last active
April 22, 2018 16:05
-
-
Save Kcko/4dd72ebc62b2a40b9c6f75aeac582a99 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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