javascripttwitter-flight

Expose function variables, locally, within component


I have a flightJS component (don't start) and need a way to expose the translated text from bindTranslations after my component has been initialized so that local functions can access the translated values. This is pseudo code of how I would like it to work, but my JS knowledge is failing me :(

function paymentForm() {
  this.bindTranslations = function() {
    var buttonText = I18n.t('js.process_payment_button');
    var paragraphText = I18n.t('js.process_payment_paragraph');

    return {
      button: buttonText,
      paragraph: paragraphText
    }
  };  

  this.handlePaymentState = function() {
    this.select('submitButtons').val(buttonText);
    this.select('paymentParagraph').val(paragraphText);
  }

  this.after('initialize', function() {
    this.bindTranslations();
  }
}

export default paymentForm;

Solution

  • Just move declarations of buttonText and paragraphText up one level to parmentForm. They will be captured in closure in bindTranslations and handlePaymentState:

    function paymentForm() {
      var buttonText;
      var paragraphText;
      this.bindTranslations = function() {
        buttonText = I18n.t('js.process_payment_button');
        paragraphText = I18n.t('js.process_payment_paragraph');
    
        // ...