在 ember 中出现未捕获的错误

Getting uncaught error in ember

当我为某些任务执行右键单击选项超过 5(大约)次时,它显示如下未捕获的错误:

Uncaught TypeError: Cannot read property 'find' of undefined
    at Class.<anonymous> (core.js:21487)
    at fn (core.js:7779)
    at DeferredActionQueues.flush (core.js:7723)
    at Backburner.end (core.js:7738)
    at Backburner.run (core.js:7748)
    at executeTimers (core.js:7824)
    at core.js:7822

在那个地方我有以下代码:

Ember.run.later(view, function () {
    this.$().find('menu-item:eq(0)').focus();
}, 125);

任何人都可以告诉我为什么会出现此错误,我需要在右键单击任务 "n" 次时避免此错误。我是 ember 的新手。您的帮助将不胜感激。提前致谢。

这是一个简单的 javascript 问题。在第二行 this.$() returns undefined,所以它不能调用 .find on undefined.

更有趣的是为什么 this.$()是未定义的。可能您在组件中有此代码,并尝试访问本地 jQuery instance。但是你在匿名 function(){} 中调用它,这会破坏你的 this-context(因为它得到了一个新的)。

这里最好的解决方案是使用箭头函数:

Ember.run.later(view, () => {
  this.$().find('menu-item:eq(0)').focus();
}, 125);

这可以防止外部 this 上下文,这很好。另一种选择是保存这个:

const self = this;
Ember.run.later(view, function () {
  self.$().find('menu-item:eq(0)').focus();
}, 125);

或者你可以.bind(this):

Ember.run.later(view, (function () {
  this.$().find('menu-item:eq(0)').focus();
}).bind(this), 125);

我绝对可以推荐第一个选项,尤其是在使用 ember(-cli) 时,它无论如何都会为您提供转译。