I struggle to find a good way to make a custom element communicate with its surroundings. So far, my google-karma is low and I haven't found anything which describes a good architecture for custom elements in Knockout.
As always, what's considered a good architecture depends ;-)
Update: I created a fiddle trying to explain what I have in mind.
In my case:
- I want the custom element to be truly autonomous.
- It should just work when added to a view, without errors.
- It should not communicate directly with any services, or any other outside components at all.
Given a custom element with one save-button, which should be activated only after something has changed, we could pass a coordinator like this:
function CustomElement(params) {
var coordinator = params.coordinator;
var enabled = this.enabled = ko.observable(false);
this.save = function() {
coordinator.save();
}
coordinator.onchange(function(hasChanges) {
enabled(hasChanges);
});
}
Where the parent view-model defines the coordinator:
function ParentView() {
this.coordinator = new CustomElementCoordinator();
}
And pass it via params:
<custom-element params="coordinator: coordinator"></custom-element>
Then I'm thinking that the coordinator should be defined in the same directory as the custom element:
custom-elements
- custom-element
- coordinator.js
- model.js
- template.html
What do you think? Am I onto something, or do I approach this incorrectly?