避免使用下划线js中的全局变量

时间:2015-03-27 13:10:37

标签: javascript html underscore.js template-engine

使用underscorejs时遇到问题。它无法正确渲染模板。看起来传递的变量需要是全局的,但这是真的吗?我想避免这个。我收到此错误:未捕获的ReferenceError:未定义项目。如果我使用而不是 var items ,那么事情就可以了。但我想避免这种情况。我该如何解决?

此代码改编自此question

的index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Title</title>

        <script data-main="index" src="require.min.js"></script>
    </head>
<body>
<script id='template' type="text/x-underscore">
<table cellspacing='0' cellpadding='0' border='1' >
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <%
        // repeat items 
        _.each(items,function(item,key,list){
          // create variables
          var f = item.name.split("").shift().toLowerCase();
      %>
        <tr>
          <!-- use variables -->
          <td><%= key %></td>
          <td class="<%= f %>">
            <!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
            <h3><%- item.name %></h3>
            <p><%- item.interests %></p>
          </td>
        </tr>
      <%
        });
      %>
    </tbody>
  </table>
</script>

<div id="target"></div>
</body>
</html>

index.js:

var application = {
    initialize: function() {
      this.load();
    },
    jsPool: [
     'jquery-1.11.2.min.js',
     'underscore-min.js',
    ],
    load: function() {
      define(
        this.jsPool,
        this.onReady
      );
    },
    onReady: function() {
      render();
    }
};

application.initialize();

function render() {
  var items = [
      {name:"Alexander"},
      {name:"Barklay"},
      {name:"Chester"},
      {name:"Domingo"},
      {name:"Edward"},
      {name:"..."},
      {name:"Yolando"},
      {name:"Zachary"}
  ];

  var template = $("#template").html();
  $("#target").html(_.template(template,{items:items}));
}

1 个答案:

答案 0 :(得分:2)

我对_.template() API的读取是它返回一个函数,您可以通过使用数据元素调用它来执行该函数。试试_.template(template)({items:items})。简化演示是内联的。

var render = function() {
  var items, templateStr, templateFunction, rendered;
  items = [
      {name:"Alexander"},
      {name:"Barklay"},
      {name:"Chester"},
      {name:"Domingo"},
      {name:"Edward"},
      {name:"..."},
      {name:"Yolando"},
      {name:"Zachary"}
  ];

  templateStr = $("#template").html();
  templateFunction = _.template(templateStr);
  rendered = templateFunction({myItems:items});
  $("#target").html(rendered);
}

render();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>

<script id='template' type="text/x-underscore">
<% _.each(myItems, function(item, key, list) { %>
<p>item.name: <%= item.name %></p>
<% }); %>
</script>

<div id="target"></div>