0

I am trying to use the [jQuery Tiny Pub/Sub][1]. However, I didn't even manage to use the code below to run a function on html. For example, how do I call publish1. How should I do that? Thanks.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  /*    
        jQuery pub/sub plugin by Peter Higgins ([email protected])
  */
  (function($) {
   var topics = {};

   $.publish1 = function(topic, args) {
    if (topics[topic]) {
     var currentTopic = topics[topic];

     for (var i = 0, j = currentTopic.length; i < j; i++) {
      currentTopic[i].apply($, args || []);
     }
    }
   };

   $.subscribe1 = function(topic, callback) {
    if (!topics[topic]) {
     topics[topic] = [];
    }

    topics[topic].push(callback);

    return {
     "topic": topic,
     "callback": callback
    };
   };
</script>
1
  • have you tried $.publish1() ? Commented Sep 6, 2014 at 10:14

1 Answer 1

0

I may be missing something, but the code as posted is an incompelte function. You need to close the anonymous function's brace and the bracket and then probable call it. In other words add the following to the end of the script block: })(jQuery); giving

<script>
(function($) {
   var topics = {};

   $.publish1 = function(topic, args) {
    if (topics[topic]) {
     var currentTopic = topics[topic];

     for (var i = 0, j = currentTopic.length; i < j; i++) {
      currentTopic[i].apply($, args || []);
     }
    }
   };

   $.subscribe1 = function(topic, callback) {
    if (!topics[topic]) {
     topics[topic] = [];
    }

    topics[topic].push(callback);

    return {
     "topic": topic,
     "callback": callback
    };
   };
})(jQuery);
</script>

I am not familar with the plugin you name, but the usual idea behind this in jQuery plugins is to create an anonymous function with $ as the param then call it with jQuery` as the argument, in case jQuery is running in noConflict mode.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, TechnoKnol and Adam. @Adam, I indeed missed to add the })(jQuery);. My problem though is how should I call the function on the html side. I have tried the following to no avail. <html> <body onLoad='$.publish1();'> ...
I think this is pretty much the answer to my query. stackoverflow.com/questions/2672355/… by Reigel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.