How to pass array of arguments to $.publish

Hi,

I got this pubsub class from a tutsplus video:

'use strict';
function PubSubs() {}

/**
 * Register the topics
 * @param topic
 * @param callback
 */
PubSubs.prototype.subscribe = function( topic, callback, context ) {
    this._topics = this._topics || {};
    this._topics[topic] = this._topics.topic || [];
    this._topics[topic].push( { "callback": callback, "context": context });
};

PubSubs.prototype.publish = function( topic, aParams ) {
    this._topics[topic].forEach( function( subscription ) {
       subscription.callback.apply( subscription.context, aParams );
    });
};

Open in new window


But when I try this to pass in an array of arguments:
MyUT.oPubSubs.publish( 'updateFinalCostAndPaymentPlans', ['setgetcalc'] );

I get a string not an array:
MyUT.oPubSubs.subscribe( 'updateFinalCostAndPaymentPlans', function(aParams) {
   aParams; //this is a string not an array
}

Am I not supposed to be passed an array because the .apply only accepts an array, doesn't it?

I was looking at this example from the Mozilla site:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fapply
/* min/max number in an array */
var numbers = [5, 6, 2, 3, 7];

/* using Math.min/Math.max apply */
var max = Math.max.apply(null, numbers); /* This about equal to Math.max(numbers[0], ...)
                                            or Math.max(5, 6, ...) */
var min = Math.min.apply(null, numbers);

/* vs. simple loop based algorithm */
max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max) {
    max = numbers[i];
  }
  if (numbers[i] < min) {
    min = numbers[i];
  }
}

Open in new window


And the argument numbers is passed as an array. How come my $.subscribe doesn't receive an array but a string?

Thanks and Father God bless<><,
Victor
Victor KimuraSEO, Web DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Slick812Commented:
I beleive in Javascript, that JSON is interpreted by use of the equal sign as -


 var array1 = ["new", "old"];

you can try this instead

var ary = ['setgetcalc'];
MyUT.oPubSubs.publish( 'updateFinalCostAndPaymentPlans',  ary );
0
Victor KimuraSEO, Web DeveloperAuthor Commented:
No, unfortunately, that didn't work. :( Any other suggestions?
0
Slick812Commented:
OK,  At fist , I thought that you knew for sure that the  .prototype.publish  method used an ARRAY for the second parameter "aParams", I have looked more closely at the code that you posted, and in the   .prototype.publish  method, it ONLY passes the  aParams to another method, and a "callback" method at that. So the actual use of the "aParams" may be for any "type", since I can not see that code.

The line that uses it is -
     subscription.callback.apply( subscription.context, aParams );

as far as I can see, the "name " of the callback method is set in this -
      prototype.subscribe = function( topic, callback, context ) {

In some "callback" methods, the second parameter is method or name of a method to gather data (parameters), although this does not look like that, but whatever variable in your test that evaluates to a "string" type is NOT the passed variable "ary" , , in this line -
MyUT.oPubSubs.publish( 'updateFinalCostAndPaymentPlans', ary );

Since this uses a redefinition of the  
   function PubSubs()

using many .prototype  I hope there is sample code from the writers of this code that shows you IF you need to call the publish , method and if you do , then also,  HOW to code the parameters for publish,

this depends on this -
    subscription.callback.apply

but I see NO code for the subscription object.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Slick812Commented:
I was lookin at another thing I did, and I realized that I had NOT made a good analysis of what the operations are in your -
    PubSubs.prototype.publish
method, I set up a test page to see If I could figure out, what was wrong, and As I tried to access the -
      this._topics[topic][0].callback
I always got an undefined, and yet in the subscribe it should be properly set with -
    this._topics[topic].push( { "callback": callback, "context": context });
to place it in that Array, so type tested this._topics[topic], and it was NOT an array, WHAT! !

so I looked at the line that should create an array -
    this._topics[topic] = this._topics.topic || [];
and It DOES NOT create and array, so I changed it to -
     this._topics[topic] = this._topics[topic] || [];

And Now it works for me in firefox.



I will admit that the operations in this -
      this._topics[topic].forEach( function( subscription ) {
          subscription.callback.apply( subscription.context, aParams );
         });

are so abstracted
(not referring to any thing specific, but other references in derived extractions from the array, like the subscription)
that I could not have any way to know what might be wrong.
0
Victor KimuraSEO, Web DeveloperAuthor Commented:
Update: I found one library that allows passing of variables to the subscribe. I haven't tested it myself. I think it's coded with CommonJS modules.

http://amplifyjs.com/api/pubsub/

Thanks Slick812 for your help. I guess I'll take a look at how amplify coded theirs when I have time to learn how to pass variables in the other pubsub lib.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Victor KimuraSEO, Web DeveloperAuthor Commented:
The amplifyjs pubsub lib I think will resolve this problem. I couldn't find out why the other pubsub couldn't work though.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.