在ember中获得未被捕获的错误

Aak*_*mar 1 javascript ember.js

当我为某项任务执行右键单击选项超过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
Run Code Online (Sandbox Code Playgroud)

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

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

任何人都可以建议我为什么会出现这个错误,我需要避免这个错误,同时右键单击任务"n"的时间也是如此.我是余烬的新手.您的帮助将不胜感激.提前致谢.

Lux*_*Lux 5

这是一个简单的JavaScript问题.在第二行this.$()返回undefined,因此它无法调用.findundefined.

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

这里最好的解决方案是使用箭头功能:

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

这可以防止外部this环境,这很好.另一个选择是保存这个:

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

或者你可以.bind(this):

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

我绝对可以推荐第一个选项,特别是在使用ember(-cli)时,无论如何都可以进行转换.