我正在尝试清除代码镜像文本的所有标记。标记已创建,调用
ret = codemirror.markText(..);
histMarks.push(ret);
要删除所有标记,我们将分别清除每个标记:
foreach( histMarks, i.clear() ); // this is pseudocode
是否有更有效的删除所有标记的方法?
如果您确实要寻找一种“ clearAllMarks”功能,则有一种稍微更有效的方法。您甚至被迫自己在阵列中捕获并存储所有标记的全部原因是因为它们没有存储在codemirror实例中的任何位置。这表明他们对.clear所做的任何操作都是独立的(也就是说,每个TextMarker都具有存储清除所需的所有信息)。确定之后,我们可以看一下markText()和.clear函数:
function markText(from, to, className, options) {
from = clipPos(from); to = clipPos(to);
var marker = new TextMarker("range", className);
if (options) for (var opt in options) if (options.hasOwnProperty(opt))
marker[opt] = options[opt];
var curLine = from.line;
doc.iter(curLine, to.line + 1, function(line) {
var span = {from: curLine == from.line ? from.ch : null,
to: curLine == to.line ? to.ch : null,
marker: marker};
line.markedSpans = (line.markedSpans || []).concat([span]);
marker.lines.push(line);
++curLine;
});
changes.push({from: from.line, to: to.line + 1});
return marker;
}
TextMarker.prototype.clear = operation(function() {
var min, max;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (span.from != null) min = lineNo(line);
if (span.to != null) max = lineNo(line);
line.markedSpans = removeMarkedSpan(line.markedSpans, span);
}
if (min != null) changes.push({from: min, to: max + 1});
this.lines.length = 0;
this.explicitlyCleared = true;
});
我还没有包含所有代码,所以请您自己仔细阅读(codemirror.js),但是您应该注意的是,所有方法实际上都在做这项工作,以确保如果您正在调用clear,那么它将从正确的位置删除标记,因为没有理由不能将相同的css类添加到不同的位置行使用不同的标记...并且清除一个不应同时清除两者。该方法还更新了changes数组,该数组只是更改了哪些行的记录。
由于我们正在执行“全部清除”操作,因此我们实际上并不关心删除某些标记而不是其他标记,因此不需要弄清楚标记影响的范围。另外,由于markText没有副作用,因此没有其他可重置的内容,因此,您要做的就是删除css类。
因此,为了获得更快的清除速度,您仍然必须存储标记或使用标记应用的类,这样您就可以执行以下操作之一:
如果仍然存储标记:
for (var i = 0;i<markers.length;i++)
$('.handleToCodeMirrorEditor').removeClass(markers[i].style);
如果您只存储类:
$('.handleToCodeMirrorEditor').removeClass(classes.join(" "));
基准测试:虽然我很清楚有效的基准测试通常是一项棘手的任务,但我认为至少要对各种方法进行少量测试是值得的。我设置了一个测试,在其中添加了一定数量的标记,每个标记都应用了不同的类(按索引递增)。然后,我运行并计时了3种不同的方法来分别删除这些标记。我以不同的顺序多次运行每个测试,以确保结果一致。我比较了3种方法:
对于删除100个标记,结果如下:
297ms .clear
160ms .removeClass on each markerStyle
153ms .removeClass single call
对于1000个标记:
4891ms .clear
2677ms .removeClass on each markerStyle
2572ms .removeClass single call
//for marking a text and storing it
var cursor = this.instance.getSearchCursor(val);
var scopedInstance = this;
while (cursor.findNext())
{
this.histMarks.push(scopedInstance.instance.markText(cursor.from(), cursor.to(), { className: 'highlight' }));
}
//for removing a marked text by specific intention
for (var i = 0;i < this.histMarks.length;i++)
{
for (var j = 0;j < this.histMarks[i].lines.length;j++)
{
if(this.histMarks[i].lines[j].text.includes(val))
{
this.histMarks[i].clear();
this.histMarks.splice(i, 1);
}
}
}