【问题标题】:$item is not defined$item 未定义
【发布时间】:2016-05-01 14:51:00
【问题描述】:

我的应用程序使用它并且在Knockout 3.4.0 下的$item 字段存在问题。我需要访问parentList,它存储了被拖到另一个列表的项目的原始父元素。

下面的代码不会在最新版本的 Knockout 中运行,jQuery 模板是它的依赖项之一。我正在寻找原因、解决方案或解决方法。

JSFiddle 附详细示例:http://jsfiddle.net/piglin/UAcC7/1837/

Uncaught ReferenceError: Unable to process binding "template: function (){return { name:'rowTmpl',foreach:$data.children,templateOptions:{ parentList:$data.children}} }"
Message: Unable to process binding "template: function (){return { name:'cellTmpl',foreach:$data.children,templateOptions:{ parentList:$data.children}} }"
Message: Unable to process binding "sortableItem: function (){return { item:$data,parentList:$item.parentList} }"
Message: $item is not defined

ko.bindingHandlers.sortableList = {};
ko.bindingHandlers.sortableItem = {
  init: function(element, valueAccessor) {
    var options = valueAccessor();
  }
};
var viewModel = function() {
  var self = this;
  self.children = ko.observableArray(
    [{}]
  );
};
ko.applyBindings(new viewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

<div data-bind="template: { name: 'tmpl', foreach: $data.children, templateOptions: { parentList: $data.children } }">
</div>

<script id="tmpl" type="text/html">
  <div data-bind="sortableItem: { item: $data, parentList: $item.parentList }">
  </div>
</script>

【问题讨论】:

  • 你能用 Knockout 模板代替吗?
  • 尝试在 tmpl 内部和 sortableItem 绑定处做 parentList: $parent.children 而不是 parentList: $item.parentList
  • 在模板 foreach 绑定中,您可以使用$parent 访问父视图模型。所以你可以使用$parent.children 而不是$item...

标签: knockout.js knockout-2.0 jquery-templates knockout-3.0 knockout-templating


【解决方案1】:

真正的问题是在将 HTML 文档附加到我的 Knockout JS 页面时,没有加载 jQuery templates 插件。

我已经正确配置了 RequireJS,它似乎是 Knockout 生命周期的问题,我需要在 activate 阶段加载 jQuery templates 依赖项,我正在编写一个代码示例来实现这一点。

【讨论】:

    【解决方案2】:

    您的模板名称似乎是“cellTmpl”,但在绑定中您称为名称:'tmpl'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多