Skip to content

Preserve internal functions in stringified view #1042

@jcubic

Description

@jcubic

I have an idea for a new feature for jQuery Terminal

When you stringify a view, all functions get removed. It would be nice to have a feature where they are preserved by serialization.

  • terminal signature
  • Finalize options in echo

Possible implementation

Symbols can't be used, but maybe a special object:

function internal(type) {
  return {'@': type};
}

And there can be a mapping of those symbols. The type will be a unique string that identifies the function, and it will be saved in an object.

The view can have functions, but they can have the toJSON property added.

const map = new Map();

function serializable_function(type, fn) {
   map.set(type, fn);
   fn.toJSON = function() {
       return internal(type);
   };
   return fn;
}

const data = {
    finalize: serializable_function('finalize_command', function(div) {
       div.addClass('terminal-command');
    })
};
JSON.stringify(data);
// '{"finalize":{"@":"finalize_command"}}'

And object.finalize can be wrapped with:

function unserialize_function(object) {
    if (!object || typeof object !== 'object' || is_function(object)) {
        return object;
    }
    if ('@' in object) {
       var key = (object['@'];
       if (!map.has(key)) {
           throw new Error('Invalid serialized object');
       }
       return map.get(key);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions