Triggers a custom event defined in a Tracker object. Data can be appended to the custom event by passing in an object with as many property/value pairs as required.
Note: triggerEvent cannot be used to trigger any of the standard application events, for example, when an item is added to the cart or the product details page is viewed. Instead, you should use addTracker() to work with those events.
EXAMPLE 2
The following example shows how you might use triggerEvent() to track when a user compares items on the website. This example is divided between two files: Company.CompareProductsExtension.MainModule.js, which corresponds to the main module file; and MainModule.View.js, which is a view file.
Note: The examples use a fictitious third-party tracking service called _externalService. Usage of a third-party provider or service for tracking purposes requires separate steps to set up and implement.
In the main module file, in the mountToApp() function, you instantiate the Environment component and create an object in which you declare a custom event listener function called compareProductsDone. Inside the function, the underscore function _.map is used to create an array of item names and skus. You then call the appropriate method of the external service (represented here with _externalService) in which you want to track the action, in this case logCommerceEvent().
// ...
mountToApp: function mountToApp(container) {
var environment = container.getComponent('Environment');
var myTracker = {
compareProductsDone: function(data) {
var products = _.map(data.items, function(item) {
return {
name: item.name,
sku: item.sku
}
});
_externalService.logCommerceEvent('productscompare', {products.products});
}
}
environment.addTracker(myTracker);
}
// ...
In the view file (based on the SCView component), define a getEvents() function to bind the click event on a HTML element to the method that will do the comparison, onCompareProductsAction(). In the onCompareProductsAction() method, triggerEvent() is called with the custom event listener function as the first argument, and a list of the items for comparison as the second argument.
this.compareItems is an ancilliary function that redirects to a comparison page. In this case, it expects a list of internal IDs of the items for comparison, which we can get with the _.pluck() function.
// ...
MainView.prototype.getEvents = function() {
return {
'click [data-action="compare-products"]': 'onCompareProductsAction'
}
}
// Function called by the click event on the element with the data attribute 'compare-products'.
MainView.prototype.onCompareProductsAction = function() {
this.environment.triggerEvent('compareProductsDone', { items: this.itemsAddedToTheComparison });
this.compareItems(_.pluck(this.itemsAddedToTheComparison, 'internalid'));
}
MainView.prototype.compareItems = function(items) {
// Compare the items.
}
// ...