在我的 Ember 应用程序中,我有一些要执行的 jQuery 代码(基于粘贴到输入框)
我的问题是我在我的代码中使用了“一个”,但它被执行了不止一次。根据 jQuery 文档,它应该只被调用一次。
didRender: function() {
var self = this;
var $inputs = Ember.$("input[id*=my-field]");
$inputs.on("paste", function() {
var $this = Ember.$(this);
var originalValue = $this.val();
$this.val("");
$this.one("input", function() {
// Why is this getting invoked more than once ?
// Contains code which splits & sets value to multiple textboxes like
//$inputBox.val('SPLITTED_PASTED_VALUE');
});
});
}
最佳答案
您看到此问题的原因是每次 ember 重新呈现您的组件/ View 时,它都会重新执行 didRender Hook 。
因为您要附加 jquery 事件的输入元素在渲染过程中持续存在,所以事件不断被添加。 .one()
确实只执行一次,正如预期的那样,但实际上您已经多次应用了 .on('paste')
,这意味着每次粘贴中,.one()
又被加了一次。
我的最终建议 - 停止使用 jquery。将 jquery 和 ember 混合在一起会导致更难追踪的奇怪事情发生。
如果那不可能,则更改调用粘贴事件的方式。 当加载组件/ Controller 时,您的文本框很可能只呈现一次。 如果是这种情况,请使用 didInsertElement将 jquery 监听器应用于元素。
didInsertElement: function() {
var self = this;
var $inputs = Ember.$("input[id*=my-field]");
$inputs.on("paste", function() {
var $this = Ember.$(this);
var originalValue = $this.val();
$this.val("");
$this.one("input", function() {
//Manipulations here
});
});
}
此外,请考虑您是否甚至需要 one('input')
事件。它似乎在粘贴后立即执行,因此您可以删除它并在清空值后处理您的操作。
关于javascript - Ember jQuery "one"事件处理程序被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51612586/