Correctly Suppressing Warnings in DataTables?

前端 未结 6 2125
小蘑菇
小蘑菇 2020-12-24 12:13

I\'m trying to correctly suppress warnings (alerts) in DataTables. The standard behavior of DataTables is to throw a javascript alert when an error occurs; however, this is

6条回答
  •  囚心锁ツ
    2020-12-24 12:51

    NB: This answer applies to dataTables 1.9.x!

    For $.fn.dataTableExt.sErrMode the only value there has any importance is "alert". It is "alert" or anything else. sErrMode is handled by the internal dispatcher function _fnLog, in v1.9.2 about line 4575 in media/js/jquery.dataTables.js :

    function _fnLog( oSettings, iLevel, sMesg )
    {
        var sAlert = (oSettings===null) ?
            "DataTables warning: "+sMesg :
            "DataTables warning (table id = '"+oSettings.sTableId+"'): "+sMesg;
    
        if ( iLevel === 0 )
        {
            if ( DataTable.ext.sErrMode == 'alert' )
            {
                alert( sAlert );
            }
            else
            {
                throw new Error(sAlert);
            }
            return;
        }
        else if ( window.console && console.log )
        {
            console.log( sAlert );
        }
    }
    

    Unfortunelaty, there is no way to override dataTables internal functions, believe me - I have tried, not possible with prototyping or anything else. You can read the author Allan Jardines own comment to that here :

    I'm sorry to say that due to how DataTables is constructed at the moment, it's not possible to override an internal function using Javascript outside of DataTables scope. This is something that will be addressed whenever I get around to doing the 2.x series (which might be a while off!) - but at present you would need to alter the core.

    One could think that : Hey, perhaps the iLevel-flag can be changed somewhere in the settings? Again, unfortunately no. iLevel is hardcoded in each internal call to _fnLog.

    It is somehow disappointing we have to choose between ugly alerts and completely halt of execution, because an error is thrown. A simply override of window.onerror does not work either. The solution is to modify _fnLog, simply comment out the line where the custom error is thrown :

    else
    {
      // throw new Error(sAlert); <-- comment this line
    }
    

    And the execution continues if you have $.fn.dataTableExt.sErrMode = 'throw' (anything else but "alert") and if errors occurs. Even better, one could need those thrown errors in other situations, set a flag outside, like

    window.isDebugging = true;
    

    and

    else
    {
      if (!window.isDebugging) throw new Error(sAlert); 
    }
    

    This is not a "hack" in my opinion, but overruling of a general not avoidable jQuery dataTables behaviour that sometimes is not satisfying. As Allan Jardine himself write in the above link :

    Why can't you just modify the source? That's the whole point of open source :-)

提交回复
热议问题