使用下划线未定义变量时抛出/捕获错误

时间:2013-12-02 20:08:52

标签: javascript underscore.js

我想知道在我的模板中没有定义变量时是否有任何解决方案可以抛出错误?

示例:

function hello() {
    var data = { foo: 'hello' };

    //data.bar is undefined, data.bar will be replaced by an empty string by underscore
    var render = _.template('<p><%= data.foo %><%= data.bar %></p>', {data: data}); 

    //Rendering okay? true|false
    //if (render...)

}

如果在调用_.template函数后未定义变量data.boo,我想抛出错误。你知道是否有可能做那样的事情吗?我检查了文档并且遗憾地找不到任何有趣的东西......

由于

3 个答案:

答案 0 :(得分:2)

无论好坏,Underscore都会为您为顶级属性执行此操作:

var data = { foo: 'hello' };
var rendered  = _.template('<p><%= foo %><%= bar %></p>', data);
// throws ReferenceError: bar is not defined

这是因为Underscore模板使用with,因此顶级属性被视为变量。如果你想在子对象属性上出错,你需要自己添加它,也可以使用with

var data = { foo: 'hello' };
// throw
var rendered  = _.template('<% with (data) { %><p><%= foo %><%= bar %></p><% } %>',
    { data: data });

或者您可以使用明确的throw,例如

<% if (data.bar === undefined) throw "No bar!"; %>

在模板的开头。但实际上,你为什么要这样做呢?如果您知道要检查的是什么,那么使用明确的预渲染检查并在那里处理它会更好,并避免在控制流中使用错误:

var rendered;
if (data.foo !== undefined) rendered = _.template("...", { data: data });
else {
    // do something else
}

答案 1 :(得分:0)

就像@mechanicalfish所说,你试图做的事似乎不正确。您应该验证模板外部的数据。在任何一种情况下,这都是你要求的:

function hello() {
    var data = { foo: 'hello' };

    //data.bar is undefined, data.bar will be replaced by an empty string by underscore
    var render = _.template('<p><%= data.foo %><% ' +
      '  if (!data.bar) { ' +
      '    throw "data.bar is undefined" ' +
      '  } else { ' +
      '    print(data.bar) ' +
      '  } ' +
      ' %></p>', {data: data}); 

    //Rendering okay? true|false
    //if (render...)

}

答案 2 :(得分:-1)

JavaScript已尝试/捕获支持。

function hello() {
    var data = { foo: 'hello' };

   try {

    //data.bar is undefined, data.bar will be replaced by an empty string by underscore
    var render = _.template('<p><%= data.foo %><%= data.bar %></p>', {data: data}); 
    } catch (e){
          throw "data.bar is undefined";
    }


}