Labs/Ubiquity/Parser 2 API Conversion Tutorial: Difference between revisions

Line 67: Line 67:


=== Using semantic roles in <code>preview</code> and <code>execute</code> ===
=== Using semantic roles in <code>preview</code> and <code>execute</code> ===
As arguments are specified using semantic roles, arguments are then passed to the <code>preview</code> and <code>execute</code> methods based on their arguments as well. Both methods are handed an object with the semantic roles as the keys, and the argument data as the values, e.g.
  { object:    { text: 'chicken',
                  data: 'chicken',
                  ... },
    instrument: { text: 'goo',
                  data: 'Google',
                  ... }
  }
Note that the structure of the argument data itself (with requisite properties <code>text</code>, <code>data</code>, and <code>html</code>) is the same as with the Parser 1 API.
Instead of handing the direct object's data and the other arguments' data separately to <code>preview</code> and <code>execute</code>, Parser 2 hands it to them together as one argument:
'''Parser 1 (old) API:'''
  CmdUtils.CreateCommand({
    ...
    preview: function(pblock, object, modifiers) {
      var data = {};
      data.query = object.text;
      data.engine = modifiers.using.text;
      pblock.innerHTML = CmdUtils.renderTemplate(
                          "Searching for ${query} using ${engine}.",
                          data );
    },
    execute: function(object, modifiers) {
      var data = {};
      data.query = object.text;
      data.engine = modifiers.using.text;
      displayMessage(CmdUtils.renderTemplate(
                      "Searching for ${query} using ${engine}.",
                      data );
    },
    ...
'''Parser 2 (new) API:'''
  CmdUtils.CreateCommand({
    ...
    preview: function(pblock, args) {
      var data = {};
      data.query = args.object.text;
      data.engine = args.instrument.text;
      pblock.innerHTML = CmdUtils.renderTemplate(
                          "Searching for ${query} using ${engine}.",
                          data );
    },
    execute: function(object, args) {
      var data = {};
      data.query = args.object.text;
      data.engine = args.instrument.text;
      displayMessage(CmdUtils.renderTemplate(
                      "Searching for ${query} using ${engine}.",
                      data );
    },
    ...
As always, it is best to first check whether the requisite arguments were filled in the parse before using it.


=== Making your command localizable ===
=== Making your command localizable ===
308

edits