Book Image

Knockout.JS Essentials

Book Image

Knockout.JS Essentials

Overview of this book

Table of Contents (16 chapters)
KnockoutJS Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Building custom events


Sometimes we need to make two or more entities of our application communicate with each other, that are not related. For example, we want to keep our cart independent of the application. We can create custom events to update it from the outside and the cart will react to this event; applying the business logic that is required.

We can split the event in two different events: the click and the action. So when we click on the up arrow to add a product, we fire a new custom event that handles the addition of a new unit, and the same to remove it. This give us more information about what is happening in our application, and we realize that a general meaning event such as click just gets the data and sends it to a more specialized event handler that knows what to do with it. This means we can reduce the number of events to just one.

  1. Create a click event handler at the end of the viewmodel.js file that throws a custom event:

    $(document).on("click", ".add-unit", function() ...