mercredi 11 mars 2015

Jquery syntax explanation for PubSub Design Pattern

In my quest to grasp better some Javacript and jQuery concepts, I ran accross the following snippet of code.



var o = $( {} );
$.subscribe = o.on.bind(o);
$.unsubscribe = o.off.bind(o);
$.publish = o.trigger.bind(o);
// Usage
$(document.body).on( 'click', function() {
// ...yadada
$.publish( 'clicketyClack' ); // Think Rocky Balboa yelling out the window: "Hey yo!"
});

// And some dude listening patiently for Rocky's voice.
$.subscribe( 'clicketyClack', function() {
console.log("You can't win, Rock");
});


Problem is I don't understand the syntax very well. What does it mean? Are we kind of extending the on namespace with the bind function?



$.subscribe = o.on.bind(o); -->
$.subscribe = $( {} ).on.bind($( {} ));


From the Jquery API:



.on( events [, selector ] [, data ], handler )
.bind( eventType [, eventData ], handler )


Thanks a lot for your help


Aucun commentaire:

Enregistrer un commentaire