如何在不提交的情况下保存表单的数据(包含多个Knockout视图模型),以便以后完成?

时间:2014-01-10 14:28:22

标签: javascript json knockout.js

我有一个足够长的表单,我想让用户保存他们的进度并在以后完成。它有多个Knockout视图模型(所有网格)以及良好的老式输入。

以下是为其中一个网格提供支持的代码示例(它们基本相同):

/**
 * Goals
 * @param {string} goal_secondary          value of input[name=goal_secondary]
 * @param {string} relation_goal_secondary value of textarea[name=relation_goal_secondary]
 */
function Goal(goal_secondary, relation_goal_secondary) {
  var self = this;

  self.goal_secondary          = goal_secondary;
  self.relation_goal_secondary = relation_goal_secondary;
}

function GoalsVM() {
  var self = this;

  // Apparently moves trigger afterAdd, but I don't want it to, so let's pretend it doesn't.
  move = false;

  self.goals = ko.observableArray([
    new Goal('', '')
  ]);

  self.addGoal = function() {
    self.goals.push(new Goal('', ''));
  }
  self.removeGoal = function(goal) {
    self.goals.remove(goal);
  }

  self.afterAdd = function(el) {
    // Don't do this stuff on move!
    if (el.nodeType === 1 && !move) {
      $(el).hide().slideDown();
    }
    // Reset move in case the user's next action is to add a new goal.
    move = false;
  }
  self.beforeMove = function(el) {
    // Tell afterAdd this is a move, not really an add.
    move = true;
  }
  self.beforeRemove = function(el) {
    if (el.nodeType === 1) {
      $(el).slideUp(function() {
        $(el).remove();
      })
    }
  }
}

以下是关联的标记:

<ul class="grid list-unstyled"
    data-bind="sortable: {
      data: goals,
      afterAdd: afterAdd,
      beforeRemove: beforeRemove,
      beforeMove: beforeMove
    }">
  <li class="row">
    <div class="col-xs-1"><span class="move">&equiv;</span></div>
    <div class="col-xs-10">
      <input class="form-control"
             data-bind="value: goal_secondary,
                        attr: { name: 'goal_secondary_' + $index() }">

      <textarea rows="3" class="form-control"
                data-bind="value: relation_goal_secondary,
                           attr: { name: 'relation_goal_secondary_' + $index() }"></textarea>
    </div>

    <div class="col-xs-1">
      <button class="btn text-danger btn-xs remove" data-bind="click: removeGoal">
        &times;
      </button>
    </div>
  </li>
</ul>

我试图关注文档中的Loading and Saving JSON data页面,但ko.toJSON(GoalsVM)会返回undefined

我也尝试过使用var Goal = function(goal_secondary, relation_goal_secondary) {…}var GoalsVM = function() {…},但我还是undefined

0 个答案:

没有答案