出错时停止Knockout

时间:2015-12-14 12:49:49

标签: javascript knockout.js

如何在淘汰赛失败时向用户发出错误警告? 而不是在控制台中默默地执行此操作:

enter image description here

2 个答案:

答案 0 :(得分:1)

看到这篇文章,我相信你想要的是:Knockout catching errors, 但是也看到片段,也许给你一些想法:

var ErrorHandlingBindingProvider = function() {
    var original = new ko.bindingProvider(); 
        //determine if an element has any bindings
    this.nodeHasBindings = original.nodeHasBindings;
    //return the bindings given a node and the bindingContext
    this.getBindings = function(node, bindingContext) {
        var result;
        try {
            result = original.getBindings(node, bindingContext);
        }
        catch (e) {
            //here you will do what you you want to do to show to user
            if (console && console.log) {
                console.log("Error in binding: " + e.message);   
            }
        }   
        return result;
    };
};

ko.bindingProvider.instance = new ErrorHandlingBindingProvider();
  

摘录:RP Niemeyer

答案 1 :(得分:0)

您可以使用try catch block。

try {
    adddlert("Welcome guest!");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.message;
}

并将错误消息传递给用户。