Reputation: 10310
I'm using Knockout and Require. I have some Knockout handlers in a separate module that I would like to use. There's no JavaScript code dependent on this module, but it is used in the data-bind attributes in the HTML.
How can I tell Require that whenever the scripts for knockout are added, it also should add this module too and that it is dependent on Knockout (it should be able to use 'ko')?
Upvotes: 0
Views: 416
Reputation: 3515
If I get you right, this is just about "defining a module with dependencies", which is a very basic requirejs thing. Take a look at the "Definition Function with Dependencies" part of the requirejs api docs.
Here is the example from the docs:
//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large",
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);
So you could do this as well in your knockout handlers, where you would pass your knockout dependency to the function. Then in every module you require knockout, you add your knockout-handlers to the dependencies within the define statement. If you didn't need them inside your module but only inside the DOM, then you didn't have to pass them to a function argument. You could just add your knockout handlers to the end of the define dependency list without adding additional arguments like this:
define(["knockout", "knockout-handlers"], function(knockout) {
//you're module using knockout,
//knockout-handlers will be available inside the dom
});
When I rethought my answer, I came to the conclusion that the circular dependency isn't a problem here. You could use a shim config for your "automatic dependency":
//within your config
requirejs.config({
shim: {
'knockout': {
deps: ['knockout-handlers']
}
}
});
//your knockout handlers module definition
define(["knockout"], function(knockout) {
return {
//Your knockout-handler module
}
});
This should load your knockout-handlers everytime you load knockout.
Upvotes: 1