窗口和警报对象/功能在Underscore模板中不可用?

时间:2015-01-18 05:19:32

标签: javascript backbone.js underscore.js

我正在尝试在我的Underscore模板中访问一个名为teams的变量,这被证明是我曾经遇到过的最困难的事情之一。但我现在的问题是 - 为什么我不能在我的模板javascript代码中调用alert()或window.alert()?

这是模板:

<script id="user-home-main-table-template" type="text/template">

    <table class="table">
    <thead>
    <tr>

        <th>Club</th>
        <th>Sport</th>
        <th>Delete?</th>

    </tr>
    </thead>
    <tbody>


    <%

    if(teams == null){
    alert('teams is null');   //alert is not defined
    window.alert('teams is null'); //window is not defined either
    var teams = {};
    }

    for(var i=0; i
    <teams.length; i++) { %>
        <tr>

            <td>
                <a class="font-big" href='/users/<%=user._id%>/teams/<%=teams[i]._id%>/teamDashboard'>
                    <%=teams[i].club %>
                </a>
            </td>
            <td>
                <a class="font-big" href='/users/<%=user._id%>/teams/<%=teams[i]._id%>/teamDashboard'>
                    <%=teams[i].sport %>
                </a>
            </td>
            <td>
                <a class="btn btn-warning" onclick=window.userHomeMainTableView.deleteTeam('<%=teams[i]._id%>');>delete</a>
            </td>
        </tr>
        <% } %>
    </tbody>
</table>
</script>

由于某种原因,此模板脚本中没有alert()和window.alert()。这有充分的理由吗?

1 个答案:

答案 0 :(得分:1)

是的,这是有充分理由的。

您的模板是在您传入的data处执行的。

来自documentation

  

评估模板函数时,传入一个数据对象,该数据对象具有与模板的自由变量对应的属性

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

因此,当您将数据发送到模板时,它不包含window属性 - 也不应该包含它!

如果您需要调试函数执行,只需在运行时执行模板执行。在Chrome中,在调试模式下,您可以&#34; Step Into&#34;按F11

相关问题