Ractive Dynamic Components

Send Data to individual component

by puneetsiet

HTML

<script id='template' type='text/ractive'>
   	<button on-click="addComponent">Add</button>
 		<div>
   		<input type="text" value="{{textdata}}" placeholder="Send Text to current component" width="900" on-blur="sendDataToCurrentComponent"/>
   	</div>
    {{#each list}}
    <input type='radio' name='{{name}}' value='{{.}}'>{{.}}
    {{/each}}
    <br>
    <dynamic/>
       
</script>

<main></main>

JavaScript

// Inspired by http://stackoverflow.com/a/31080919/405117
var mapper = {
	'A': function(instanceId){
  	var handleAData;
  	return Ractive.extend({ 
  			template: 'I am A this is my data: <ul>{{#datas}}<li>{{.}}</li>{{/datas}}</ul>',
        data: {
        	datas:[]
        },
        onrender: function() {
        
        	if (!handleAData){
          	handleAData = function(txt){
          		this.push('datas', txt);
          	}.bind(this);
          
        		r.on(instanceId, handleAData);
          }
        	
        }
  	});
  }
  ,'B': function(instanceId){
  	var handleBData;
  	return Ractive.extend({ 
  			template: 'I am B this is my array data: <ul>{{#datas}}<li>{{.}}</li>{{/datas}}</ul> <div>I am {{primitive}}</div>',
        data: {
        	datas:[],
          primitive: true
        },
        onrender: function() {
        	if (!handleBData) {
            handleBData = function(txt){
              this.push('datas', txt);
            }.bind(this);

            r.on(instanceId, handleBData);
          }
        }
  	});
  }
  
}

/* arbitrarily select a component */
function pickRandomComponent() {
	return String.fromCharCode(Math.floor(Math.random() * Object.keys(mapper).length) + 65);
}

var DynamicComponent = Ractive.extend({
    template: '<component/>',
    components: {
        component: function() {
            return this.get('name');
        }
    },
    oninit: function(){
        this.observe('name', function(){
            this.reset();
        }, { init: false});
    }
});

var Dashboard = Ractive.extend({
		template: '#template',
    components: {
    	dummy: Ractive.extend({ template: 'Welcome message' }),
    	dynamic: DynamicComponent
    },
    data: {
        foo: 'foo',
        list: ['dummy'],
        name: 'dummy',
        textdata: ''
    },
    oninit: function() {
    	this.on("sendDataToCurrentComponent", function() {
      	r.fire(this.get('name'), this.get('textdata'))
      }.bind(this));
      
   ...