util/SaveCommand.js

/**
 * @copyright 2015 Tridium, Inc. All Rights Reserved.
 * @author Gareth Johnson
 */

/**
 * A Command for saving a Widget.
 * 
 * @module bajaux/util/SaveCommand
 */
define([ 'bajaux/commands/Command',
        'bajaux/events' ], function (
        Command,
        events) {
  'use strict';

  /**
   * A Command for saving a Widget.
   *
   * @class
   * @extends module:bajaux/commands/Command
   * @alias module:bajaux/util/SaveCommand
   */
  var SaveCommand = function SaveCommand() {
    var that = this;

    // Internal flag used to indicate this is a SaveCommand.
    that.$saveCmd = true;

    Command.call(that, {
      module: 'bajaux',
      lex: 'saveCmd',
      enabled: false,
      flags: Command.flags.NONE,
      /**
       * Saves the Widget.
       *
       * @alias module:bajaux/util/SaveCommand#invoke
       * @returns {Promise}
       */
      func: function () {
        var widget = that.$widget;

        if (widget && that.isEnabled()) {
          return widget.save();
        }
      }
    });
  };

  SaveCommand.prototype = Object.create(Command.prototype);
  SaveCommand.prototype.constructor = SaveCommand;

  /**
   * Initialize the Save Command by setting a reference to the
   * associated widget.
   *
   * @inner
   * @private
   * 
   * @param  {module:bajaux/util/SaveCommand} saveCmd An instance of the Save Command.
   * @param  {JQuery} jq The jQuery wrapper for the associated Widget.
   */
  function initialize(saveCmd, jq) {
    // Set a reference to the underlying Widget so the Command can use it.
    var widget = saveCmd.$widget = jq.data("widget");

    function onModify() {
      saveCmd.setEnabled(widget.isModified());
    }

    // When the Widget is modified or unmodified, enable or disable 
    // the Command.
    jq.on(events.MODIFY_EVENT + " " + events.UNMODIFY_EVENT, onModify);
    onModify();
  }

  /**
   * @see module:/bajaux/commands/Command
   */
  SaveCommand.prototype.jq = function (jq) {
    if (jq) {
      initialize(this, jq);
    }

    return Command.prototype.jq.apply(this, arguments);
  };

  return SaveCommand;
});