-
Notifications
You must be signed in to change notification settings - Fork 68
Contexts
When you feed a spec to wire.js as input, it produces a context. The context is a Javascript Object that contains the all fully realized components that were specified in the wiring spec. The context also has methods for wiring child contexts, resolving references, and destroying the context and all the objects, etc. that were created when it was wired.
Let's look again at the simple wiring spec from the Hello Wire example.
define({
message: "I haz been wired",
helloWired: {
create: {
module: 'hello-wired',
args: { $ref: 'dom!hello' }
},
init: {
sayHello: { $ref: 'message' }
}
},
plugins: [
{ module: 'wire/dom' }
]
});
Using wire.js as an AMD plugin, we can wire the spec:
require(['wire!hello-wired-spec'], function(context) {
console.log(context);
// Components are just properties of the wired context
console.log(context.helloWired)
});
which creates the context, context
, that contains fully realized components:
-
message
- a String -
helloWired
- an object created from the AMD modulehello-wired
, whose constructor was passed a DOM node by thewire/dom
plugin's DOM reference resolver, and whoseinit()
function has been called and passed themessage
String. -
plugins
- an Array containing a single wire.js plugin,wire/dom
.
The wired
context has properties for the components from the wiring spec.
In wire.js, there is an implicit hierarchy of contexts, and there is a Root Context that is the ultimate ancestor of all the contexts you create. This context hierarchy acts a lot like a Javascript prototype chain, in that a child contexts can see components from its parent context, can override them, and can have new components not in its parent.
Any context can be used to create a child by calling context.wire(childSpec)
. Here's an example using the hello-wire.js
spec as the parent to create a child:
// First, create the hello-wire context, same as above.
require(['wire!hello-wired-spec'], function(context) {
console.log(context);
// Use the context to wire a child
context.wire({
// Child context
anotherComponent: {
// Create an instance by calling constructor with no args
create: 'my/other/component',
// Call anotherComponent.sayHowdy(message)
// Message refers to the message String in the parent context
init: {
sayHowdy: { $ref: 'message' }
}
}
}).then(function(childContext) {
console.log(childContext);
// The child can see components in its parent, similar to
// a Javascript prototype
console.log(childContext.helloWired);
// But also has its own components
console.log(childContext.anotherComponent);
// The parent *cannot* see components in the child
console.log(context.anotherComponent); // logs undefined
});
});
The childContext
will have properties for all the components in its parent context
: message
, helloWired
, and plugins
, but will also have the additional component anotherComponent
.
More coming soon
Coming soon