Publish messages
Two functions, publish()
and publishWith()
,
are used to publish messages to topics.
The publish()
function takes one parameter, the object you want to
publish. In the example below, the publish()
function will send the
data object to callback functions that are subscribed to the PAGE_READY
topic.
$.Topic(PubSub.topicNames.PAGE_READY).publish(data);
In some cases, you may need to control the context in which subscribers receive the
published data. When a publisher provides context, it is providing the subscriber with
access to data or operations the subscriber needs to do its job. To control context, use
the publishWith()
function instead of the publish()
function. The publishWith()
function takes two parameters; the first is
the object to be used as this in the subscriber’s callback function, the second is the
object you want to publish. For example, the following code publishes the billing
address as the context:
$.Topic(pubsub.topicNames.CHECKOUT_BILLING_ADDRESS).publishWith(
widget.billingAddress(), [{
message: "success"
}]);
This allows the subscriber to update the billing address with the value of this:
$.Topic(pubsub.topicNames.CHECKOUT_BILLING_ADDRESS).subscribe(
function() {
self.billingAddress(this);
}
);