Skip to content

Fields should implement fromJson  #1486

Description

@rachel-fenichel

Problem statement

Currently parsing JSON to pass to a field constructor is handled in block.js, likely because that puts it close to the other JSON code. (Lines 1215 to 1271)

Here is a sample function:

/**
 * Helper function to construct a FieldTextInput from a JSON arg object,
 * dereferencing any string table references.
 * @param {!Object} options A JSON object with options (text, class, and
 *                          spellcheck).
 * @returns {!Blockly.FieldTextInput} The new text input.
 * @private
 */
Blockly.Block.newFieldTextInputFromJson_ = function(options) {
  var text = Blockly.utils.replaceMessageReferences(options['text']);
  var field = new Blockly.FieldTextInput(text, options['class']);
  if (typeof options['spellcheck'] == 'boolean') {
    field.setSpellcheck(options['spellcheck']);
  }
  return field;
};

This code clutters up block.js without actually doing anything block-specific. Developers making new fields tend to follow this example and put more code in block.js. We'd prefer to keep code for custom fields contained.

Better would be to have FieldTextInput have a fromJson function, in field_textinput.js:

/**
 * Helper function to construct a FieldTextInput from a JSON arg object,
 * dereferencing any string table references.
 * @param {!Object} options A JSON object with options (text, class, and
 *                          spellcheck).
 * @returns {!Blockly.FieldTextInput} The new text input.
 * @package
 */
Blockly.FieldTextInput.fromJson_ = function(options) {
  var text = Blockly.utils.replaceMessageReferences(options['text']);
  var field = new Blockly.FieldTextInput(text, options['class']);
  if (typeof options['spellcheck'] == 'boolean') {
    field.setSpellcheck(options['spellcheck']);
  }
  return field;
};

Developers making custom fields would follow this pattern, and we would move all of the existing field parsing code out of block.js.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    low priorityIssues that are unlikely to be added to the developer roadmap

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions