Last active
December 20, 2015 06:18
-
-
Save elgalu/6084458 to your computer and use it in GitHub Desktop.
Decoupling event/DOM/business logic using custom jQuery events
http://flippinawesome.org/?p=662
http://jsfiddle.net/elgalu/C7kbK/
This file contains hidden or 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
| ///////////////////////////////////////////////////////////// | |
| // Creating a custom event listener on the document object // | |
| ///////////////////////////////////////////////////////////// | |
| var $doc = $(document); | |
| var $items = $('.items'); | |
| var $log = $('.log'); | |
| // DOM-related logic | |
| $doc.on('addItem', function (event, value) { | |
| $items.append('<li>New item ' + value + '</li>') | |
| }); | |
| // Business-related logic | |
| $doc.on('addItem', function (event, value) { | |
| $log.html('<p>updating backend for item ' + value + '...</p>'); | |
| //$.ajax({ ...etc... }); | |
| }); | |
| // Event-related logic | |
| $('.add-item').on('click', function (event) { | |
| var rand = Math.floor(Math.random() * 1000); | |
| $doc.trigger('addItem', rand); | |
| event.preventDefault(); | |
| }); |
This file contains hidden or 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
| <ul class="items"></ul> | |
| <button class="add-item">Add item</button> | |
| <div class="log"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment