I'm trying to implement the publish-subscribe pattern in jQuery. I have a list of divs. Some of them needs to react to various events. I want to be able to easily set (and unset) which of them needs to react to which event.
A simple example of what I want to achieve is as follows:
<div id="item1">item 1</div>
<div id="item2">item 2</div>
<div id="item3">item 3</div>
<div id="item4">item 4</div>
<button id="button1">Event 1</button>
<button id="button2">Event 2</button>
<script type="text/javascript">
$('#item1').on('event1', handleEvent1);
$('#item2').on('event1', handleEvent1);
$('#item1').on('event2', handleEvent1);
$('#item3').on('event2', handleEvent1);
//event handlers
function handleEvent1() {
$(this).addClass('event1');
}
function handleEvent2() {
$(this).addClass('event2');
}
//event triggers
$('#button1').on('click', function(e) {
$(this).trigger('event1');
});
$('#button2').on('click', function(e) {
$(this).trigger('event2');
});
</script>
Complete example at http://ift.tt/1dwlijj (not working, obviously)
I believe the reason is that the event originates outside of the elements, and thus when bubbled up it doesn't hit the elements at all. I did manage to get it working if I handle the events at the top document level, and maintain a list of elements that are subscribed to each event instead of directly linking the events to each element. This doesn't feel as tidy. Working example is at http://ift.tt/1LCnpjz
Am I implementing/understanding this design pattern correctly? Is there a better/cleaner way to achieve what I want to do?
Aucun commentaire:
Enregistrer un commentaire