0

此代码在将 coffee_input 哈希传递给咖啡脚本代码的视图上正常工作

 #if coffee_input?
 if typeof coffee_input isnt "undefined"
   mydata = JSON.parse coffee_input
   for p in mydata by 1
     if $('#'+p.name).length
       .. do stuff

但在其他页面上,我一直在浏览器中出现此错误:

TypeError: 'undefined' is not an object (evaluating 'mydata.length')

虽然我使用的是 typeof coffee_input isntundefined

我不明白。

编辑:视图代码:

= javascript_tag do
  window.coffee_input = '#{raw @js.to_json}';

@js从控制器是:

   @js = []
   @js_hash = {"name" => p.name, "hosts" => "", "services" => ""}
   @js << @js_hash
4

1 回答 1

0

解决方法:我查看了浏览器中生成的Javascript

(function() {
  jQuery(function() {
var context, g, metrics, mydata, overall, pod, _i, _len, _results;

if (typeof coffee_input !== "undefined" && coffee_input !== null) {
  mydata = JSON.parse(coffee_pods);
  _results = [];
  } // WRONG!!!!!!!!!!!!!!!
  for (_i = 0, _len = mydata.length; _i < _len; _i += 1) {
      …..

由于某种未知的原因,它将花括号放在 if 的末尾而不是 for 循环的末尾。

我只是重写了它,间距是正确的,如果不是咖啡脚本会抱怨的。

于 2013-07-19T18:25:35.230 回答