Ractive Decorator Update

by Christian Meixner

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/ractive.js"></script>

<div id="demo"></div>

<script id="tmpl" type="text/template">
<div> <b>Text</b>: {{_t('title')}} </div>
<div> <b>Text via Decorator</b>: <span as-text="_t('title')"></span> </div>
<div> <b>Text via Decorator with forced Update</b>: <span as-text="_t('title'),@shared.i18n.language"></span> </div>

<hr>
<div>
<b>Select Language</b>
{{#languages}}
<input type="radio" name="{{@shared.i18n.language}}" value="{{.}}" /> {{.}}
{{/}}
</div>
</script>

CSS

body {font-family:helvetica; font-size:12px}
div {margin:3px 5px;}

JavaScript

Ractive.WELCOME_MESSAGE = false;
console.log(Ractive.VERSION);

const ressource = {
  de: {title: 'Titel auf deutsch'},
  en: {title: 'Title in english'}
};


function i18nRactivePlugin(target) {
  function _t(key) {
    const language = target.Ractive.sharedGet('i18n.language');
    return ressource[language][key];
  }
  target.instance.helpers._t = _t;
}

Ractive.use(i18nRactivePlugin);
Ractive.sharedSet('i18n.language', 'en');

const app = new Ractive({
  el: '#demo',
  template: '#tmpl',
  data: {
  	languages:['de', 'en']
  },
  decorators: {
  	text: textDecorator
  }
});

function textDecorator (node, value) {
	node.textContent = value;
  return {
		update: function (newValue) {
			node.textContent = newValue;
    },
    teardown: function () {}
  }
}