2014-07-04 177 views
2

我正在設計一個使用工具欄附帶的CodeMirror的應用程序。由於性能原因,我不是通過異步模式或異步模式執行lint。Codemirror-linting - 是否有事件可以明確觸發linting?

我在工具欄中提供了一個圖標,點擊這個我正在解析和構造錯誤。但我堅持如何在編輯器中更新lint錯誤?

任何指針都會非常有幫助。

+0

*「我沒有通過異步或異步模式執行皮棉」*我恐怕我不明白,你能澄清嗎? (肯定有沒有兩種不同的*模式稱爲「async」和「asynch」?) –

+0

有兩種方法可以註冊lint CodeMirror.registerHelper(「lint」,「custom」,function(text){} )並設置codemirror選項lint = true。另一個是使用lintWith選項。 lintWith:{ 「getAnnotations」:myvalidator, 「async」:true, } – Chetan

回答

2

您是否嘗試過使用下面的代碼動態設置lint值?

//enable 
editor.setOption("lint",true); 

//disable 
editor.setOption("lint",false); 

你可以看到一個演示這裏JSFiddle link

2

這聽起來像沒有出現存在一個很好的功能。

創建按鈕以從外部按鈕啓動驗證很簡單。

例如[無信用] https://jsfiddle.net/AlexAtIkanow/3pVxP/

function checkFormat(editor) { 
    var success = JSHINT(editor.getValue()); 
    var output = ''; 
    if (!success) { 
     output = "Check format error:\n\n"; 
     for (var i in JSHINT.errors) { 
      var err = JSHINT.errors[i]; 
      if (null != err) { 
       output += err.line + '[' + err.character + ']: ' + err.reason + '\n'; 
      } else { 
       output += "Check format unknown error:\n"; 
      } 
     } 
     alert(output); 
    } 
    return success; 
} 

然而,這並不呈現在CodeMirror編輯器中的驗證消息的行號排水溝,這是什麼OP一直在尋找可以顯示。

爲此,您可以自定義lint附加代碼。 例如從標準插件提供的JSON-棉絨 [https://github.com/codemirror/CodeMirror/blob/master/addon/lint/json-lint.js]

1.Extract registerHelper()的主體成再現該現有功能的新的函數:

CodeMirror.registerHelper("lint", "json", function(text) { 
    return mylinthandler(text) 
} 

mylinthandler(text) { 
var found = []; 
    jsonlint.parseError = function(str, hash) { 
    var loc = hash.loc; 
    found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column), 
       to: CodeMirror.Pos(loc.last_line - 1, loc.last_column), 
       message: str}); 
    }; 
    try { jsonlint.parse(text); } 
    catch(e) {} 
    return found; 
} 
  • 關閉自動lint CodeMirror選項。

    lintOnChange:假

  • 然後,當你想皮棉,叫 mylinthandler(editor.getValue())

  • 1

    要在一行觸發皮棉:

    // trigger registered lint handler 
    editor.setOption("lint", {}); 
    
    // trigger custom lint handler defined on the fly 
    editor.setOption("lint", { 
        getAnnotations: function() { /* some smart code */ return found; } 
    }); 
    

    如果你想知道爲什麼它應該是有史以來工作時,請看addon/lint/lint.js,特別是以下幾行:

    CodeMirror.defineOption("lint", false, function(cm, val, old) { 
        ... 
        if (val) { 
         ... 
         startLinting(cm); 
        } 
        }); 
    
    3

    皮棉插件增加了一個「擴展」的方法稱爲performLint所有編輯器的情況下,與lint: { lintOnChange: false }編輯器選項結合起來,然後你可以通過調用mirror.performLint()調用棉短絨。

    如果你定義自己的皮棉方法ALA

    CodeMirror.registerHelper('lint', 'mode', (text) => { /* your cool stuff here */ }) 
    

    即會得到performLint()調用。

    相關問題