Skip to content

Instantly share code, notes, and snippets.

@darylteo
Last active October 10, 2016 20:36
Show Gist options
  • Save darylteo/12a5f9bbb63916e10e89ab2bf88d8b5b to your computer and use it in GitHub Desktop.
Save darylteo/12a5f9bbb63916e10e89ab2bf88d8b5b to your computer and use it in GitHub Desktop.
Dynamic Component for Ractive with Data propagation on the same level as data source
/*
Extension of the code found at the following SO post
http://stackoverflow.com/questions/31075341/how-to-create-ractives-subcomponents-dynamically-and-change-them-programmatical
*/
let Ractive = require("Ractive");
Ractive.components.dynamic = Ractive.extend({
template: "{{>impl}}",
components: { // you can set whatever components you need, or just use the global ones via Ractive.components },
partials: {
// this generates the dynamic component tag
// we do this so that we can use Ractive.findComponent("componentName")
impl: function() {
return "<" + this.get("name") + "/>";
},
},
data: function() {
return {
name: null,
data: {},
};
},
oninit: function() {
// not too sure what this does, but left untouched from SO post
this.observe("name", function() {
this.reset();
}, {init: false});
// here we observe all changes to the data object
// then proxy these to the dynamic component while preserving
// the appropriate keypath
this.observe("data.*", (newValue, oldValue, keyPath) => {
keyPath = keyPath.substring(5);
let component = this.findComponent();
if (component) {
component.set(keyPath, newValue);
}
});
},
});
// then use this in your template
// <dynamic type="{{type}}" data="{{data}}" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment