Applying RequireJS to components
We didn't modularize our bindings and components in the second part of the chapter. But this doesn't mean that we couldn't.
We can use RequireJS not just to create modules, but also to load files asynchronously. In our case, bindings and components don't need to return an object. When these files are loaded, they extend the ko
object and their job is done. A similar case occurs with events. We initialize events and the work is done. So these files just need to be wrapped into the define
function. Add dependencies and load them in the app.js
file as we did in the previous section.
In the case of the add-to-cart-button
component, the code in the file will be the following:
define([ 'knockout', 'models/CartProduct', 'services/CartProductService', 'services/ProductService' ],function(ko, CartProduct,CartProductService,ProductService){ ko.components.register('add-to-cart-button', { ... }); });