2016-09-25 62 views
1

在application.js中,我從ajax調用中將所有'主題'編譯在頁面上,然後單擊時,所有信息都會出現在屏幕上。在開發中一切都很好,但在生產中我得到了500個服務器錯誤。爲什麼這個函數console.log而不是一次20次?

在試圖調試時,我注意到控制檯使用.onclick調用記錄了20次。爲什麼會發生這種情況,並且是否有任何理由說明它會返回生產中的500錯誤(heroku)?

我把** **圍繞3個console.logs發生。

if(window.location.pathname === "/topics") { 
    $('.actions').click(function(e) { 
     console.log("submit"); 
    }) 

    $.ajax({ 
      url: '/topics', 
      dataType: 'json', 
      type: 'GET', 
      success: function(result) { 
       console.log(result); 
       for(var i = 0; i < result.length; i++) { 
        var title = result[i].title; 
        var level = result[i].level; 
        var id = result[i].id; 
        var favlink = '/topics/' + id + '/favorite';  
        var link = '/topics/' + id; 
        var topicInfo = {title: title, link: link}; 
        var template = compiledTopics(topicInfo); 
        $('.topic-wrapper').append(template); 



       $('.listing-topics, .favorite-topic-title').click(function(e){ 
         e.preventDefault(); 
         if($(this).hasClass("favorite-topic-title")) { 
          var heartClass = "favorited_heart_icon" 

         } 
         else if($(this).hasClass("listing-topics")) { 
          var heartClass = "unfavorited_heart_icon"; 
          $('html, body').animate({ scrollTop: 0 }, 'fast'); 

         } 
         **console.log(this);** 
         $.ajax({ 
          url: this, 
          dataType: "json", 
          type: 'GET', 
          success: function(result) { 


           var id = result.id; 
           var title = result.title; 
           var body = result.body; 
           var level = result.level 
           **console.log(level);** 

           //SHOW TOPIC and FAVTOPIC AS POPUP WHEN CLICKED 

           //Add proper favorite icon. 
           var favlink = '/topics/' + id + '/favorite';  
           **console.log(heartClass);** 
           var topicInfo = {title: title, body: body, heartClass: heartClass}; 
           var template = compiled(topicInfo); 



           $('.topic-wrapper').append(template); 

           //CLOSE TOPIC WHEN CLICKING THE GREY SURROUNDING BOX - topicClose 
           $('.topicClose').click(function(e) { 
            $('.topicClose').css("display", "none"); 
            $('.show_topic').css("display", "none"); 
           }) 

           //FAVORITE TOPIC 
           //ADD TO FAV TOPICS LIST 

           $(".unfavorited_heart_icon, .favorited_heart_icon").click(function(e) { 
            e.preventDefault(); 
            //onclick - change colors of heart 

            if ($(this).hasClass("favorited_heart_icon")) { 
             $(this).removeClass("favorited_heart_icon"); 
             $(this).addClass("unfavorited_heart_icon"); 
             urlEnd = '/unfavorite'; 
            } 
            else if ($(this). hasClass("unfavorited_heart_icon")) { 
             $(this).removeClass("unfavorited_heart_icon"); 
             $(this).addClass("favorited_heart_icon"); 
             urlEnd = '/favorite'; 
            } 
            // console.log('/topics/favorite/' + id); 
            $.ajax({ 
             url: '/topics/' + id + urlEnd, 
             type: 'POST', 
             success: function(result) { 
              location.reload(); 
             } 
            }) 

           }); 



          }, 
          error: function(err) { 
           console.log(err); 
          } 


         }) 
        }); 


      }; 

     }, 
     error: function(err) { 

     } 
    }); 

在同一js文件的底部:

var listingSource = $("#listingTopics").html(); 
var compiledTopics = Handlebars.compile(listingSource); 

主題車把模板:

<script id="listingTopics"> 
    <div> 
    <a href={{link}} class="listing-topics">{{title}}</a> 
    </div> 
</script> 

提前感謝!

編輯**

我也試過:

$.ajax({ 
       url: '/topics', 
       dataType: 'json', 
       type: 'GET', 
       success: function(result) { 
        for(var i = 0; i < result.length; i++) { 
         var title = result[i].title; 
         var level = result[i].level; 
         var id = result[i].id; 
         var favlink = '/topics/' + id + '/favorite';  
         var link = '/topics/' + id; 
         var topicInfo = {title: title, link: link}; 
         var template = compiledTopics(topicInfo); 
         $('.topic-wrapper').append(template).click(function(e) { 
          e.preventDefault(); 
          console.log($(this)) 
         }); 
       }; 
      }, 
+1

你結合你的循環內共有20個事件偵聽器。點擊所有20個。 – Xufox

+0

@ user2267175我在ajax調用之前添加了一個,它只運行一次。看起來好像是在通話中發生的事情 – gwalshington

+2

我猜「結果」大概是20個項目。在for循環中創建'click'事件處理程序時,將其綁定到類'.listing-topics,.favorite-topic-title'。當您點擊元素時,它會繼續並觸發點擊事件(20次,因爲您的結果數組中有20個項目)。我懷疑這是發生了什麼,但需要看看它來驗證。你有JSFiddle嗎? – mwilson

回答

0

我猜results大約20個項目。當您在for循環中創建您的click事件處理函數時,將其綁定到類.listing-topics, .favorite-topic-title。當您點擊元素時,它會繼續並觸發點擊事件(20次,因爲您的結果數組中有20個項目)。我懷疑這是發生了什麼,但需要看看它來驗證。你有JSFiddle嗎?

要解決此問題,請更改綁定事件處理程序的方式。您需要將其範圍限定爲類或元素的特定實例,以便事件單獨觸發,而不是一次觸發全部事件。

示例場景

var results = ["1", "2", "3"]; 


//How you're currently doing it 
for (var i = 0; i < results.length; i++) { 
    $('#container').append($('<div />', {text: results[i], class:'test-class'})); 
    $('.test-class').click(function() { 
    console.log($(this).text()); 
    }); 
} 

//Solution 
for (var i = 0; i < results.length; i++) { 
    $('#container').append($('<div />', {text: results[i], class:'test-class'}).click(function() { 
    console.log($(this).text()); 
    })); 
} 

我創造了這個情況(與你心),以幫助更好地解釋所發生的事情的簡單再生產。基本上,無論在什麼時候(按類)綁定所有事件,都會在創建時將其綁定到元素。

的jsfiddle:https://jsfiddle.net/ncrxekmq/

更新的代碼

if(window.location.pathname === "/topics") { 
    $('.actions').click(function(e) { 
     console.log("submit"); 
    }) 

    $.ajax({ 
      url: '/topics', 
      dataType: 'json', 
      type: 'GET', 
      success: function(result) { 
       console.log(result); 
       for(var i = 0; i < result.length; i++) { 
        var title = result[i].title; 
        var level = result[i].level; 
        var id = result[i].id; 
        var favlink = '/topics/' + id + '/favorite';  
        var link = '/topics/' + id; 
        var topicInfo = {title: title, link: link}; 
        var template = compiledTopics(topicInfo); 
        $('.topic-wrapper').append(template); 


       //use $.each(index, item) to loop through all of your elements and bind the click event individually instead of in one go. 
       $('.listing-topics, .favorite-topic-title').each(function (index, item) { 
        $(item).click(function(e){ 
         e.preventDefault(); 
         if($(this).hasClass("favorite-topic-title")) { 
          var heartClass = "favorited_heart_icon" 

         } 
         else if($(this).hasClass("listing-topics")) { 
          var heartClass = "unfavorited_heart_icon"; 
          $('html, body').animate({ scrollTop: 0 }, 'fast'); 

         } 
         **console.log(this);** 
         $.ajax({ 
          url: this, 
          dataType: "json", 
          type: 'GET', 
          success: function(result) { 


           var id = result.id; 
           var title = result.title; 
           var body = result.body; 
           var level = result.level 
           **console.log(level);** 

           //SHOW TOPIC and FAVTOPIC AS POPUP WHEN CLICKED 

           //Add proper favorite icon. 
           var favlink = '/topics/' + id + '/favorite';  
           **console.log(heartClass);** 
           var topicInfo = {title: title, body: body, heartClass: heartClass}; 
           var template = compiled(topicInfo); 



           $('.topic-wrapper').append(template); 

           //CLOSE TOPIC WHEN CLICKING THE GREY SURROUNDING BOX - topicClose 
           $('.topicClose').click(function(e) { 
            $('.topicClose').css("display", "none"); 
            $('.show_topic').css("display", "none"); 
           }) 

           //FAVORITE TOPIC 
           //ADD TO FAV TOPICS LIST 

           $(".unfavorited_heart_icon, .favorited_heart_icon").click(function(e) { 
            e.preventDefault(); 
            //onclick - change colors of heart 

            if ($(this).hasClass("favorited_heart_icon")) { 
             $(this).removeClass("favorited_heart_icon"); 
             $(this).addClass("unfavorited_heart_icon"); 
             urlEnd = '/unfavorite'; 
            } 
            else if ($(this). hasClass("unfavorited_heart_icon")) { 
             $(this).removeClass("unfavorited_heart_icon"); 
             $(this).addClass("favorited_heart_icon"); 
             urlEnd = '/favorite'; 
            } 
            // console.log('/topics/favorite/' + id); 
            $.ajax({ 
             url: '/topics/' + id + urlEnd, 
             type: 'POST', 
             success: function(result) { 
              location.reload(); 
             } 
            }) 

           }); 



          }, 
          error: function(err) { 
           console.log(err); 
          } 


         }) 
        }); 
       }); 

      }; 

     }, 
     error: function(err) { 

     } 
    }); 
+0

我同意這個邏輯,但是如何能夠唯一地識別我通過'this'點擊的特定實例,而不是將它與主題實例的總數相關聯?謝謝! – gwalshington

+0

在JSFiddle中創建示例場景來解釋... – mwilson

+0

添加了JSFiddle。讓我知道如果這有幫助! – mwilson

1

我想了很多,你正在使用多個事件偵聽器的分配有問題可以通過採取這些聽衆走出來解決循環和使用委託策略定義它們。

我會嘗試一些概念上類似於:

function getTopicJSON_Success(result){ 
    console.log(result); 

    for(var i = 0; i < result.length; i++) { 
     var title = result[i].title; 
     var level = result[i].level; 
     var id = result[i].id; 
     var favlink = '/topics/' + id + '/favorite';  
     var link = '/topics/' + id; 
     var topicInfo = { title: title, link: link }; 
     var template = compiledTopics(topicInfo); 
     $('.topic-wrapper').append(template); 
    } 
} 

function getJSON_Error(err){ 
    console.log(err); 
} 

if(window.location.pathname === "/topics") { 

    $('.actions').click(function(e) { 
     console.log("submit"); 
    }); 

    $('.topic-wrapper').on("click", '.listing-topics, .favorite-topic-title', function(e){ 
     e.preventDefault(); 

     // ========================= 
     // Note at this point "this" is the element that was clicked. 
     // in the ajax requrest below we will want to use $this.attr("href"). 
     // ========================= 
     console.log(this); 
     // ========================= 

     var $this = $(this); 
     var heartClass; 

     if($this.hasClass("favorite-topic-title")) { 
      heartClass = "favorited_heart_icon" 
     } else if($this.hasClass("listing-topics")) { 
      heartClass = "unfavorited_heart_icon"; 
      $("body").animate({ scrollTop: 0 }, 'fast'); 
     } 

     // ========================= 
     // Note: could be "null". 
     // Did you want one or the other specifically and not the posibility of null? 
     // ========================= 
     console.log(heartClass); 
     // ========================= 

     var getListJSON_Success = function(result){ 
      var id = result.id; 
      var title = result.title; 
      var body = result.body; 
      var level = result.level 

      console.log(level); 

      //SHOW TOPIC and FAVTOPIC AS POPUP WHEN CLICKED 

      //Add proper favorite icon. 
      var favlink = '/topics/' + id + '/favorite';  
      var topicInfo = {title: title, body: body, heartClass: heartClass}; 
      var template = compiled(topicInfo); 

      $('.topic-wrapper').append(template); 

      //CLOSE TOPIC WHEN CLICKING THE GREY SURROUNDING BOX - topicClose 
      $('.topicClose').click(function(e) { 
       $('.topicClose').css("display", "none"); 
       $('.show_topic').css("display", "none"); 
      }); 

      //FAVORITE TOPIC 
      //ADD TO FAV TOPICS LIST 
     }; 

     $.ajax({ 
      url: $this.attr("href"), 
      dataType: "json", 
      type: 'GET', 
      success: getListJSON_Success, 
      error: getJSON_Error 
     }) 
    }); 

    $('.topic-wrapper').on("click", ".unfavorited_heart_icon, .favorited_heart_icon", function(e) { 
     e.preventDefault(); 

     var $this = $(this); 
     var urlEnd; 

     if ($this.hasClass("favorited_heart_icon")) { 
      $this.removeClass("favorited_heart_icon"); 
      $this.addClass("unfavorited_heart_icon"); 
      urlEnd = '/unfavorite'; 
     } else if ($this. hasClass("unfavorited_heart_icon")) { 
      $this.removeClass("unfavorited_heart_icon"); 
      $this.addClass("favorited_heart_icon"); 
      urlEnd = '/favorite'; 
     } 

     $.ajax({ 
      url: '/topics/' + $this.attr("id") + urlEnd, 
      type: 'POST', 
      success: function(result) { location.reload(); }, 
      error: getJSON_Error 
     }); 

    }); 

    $.ajax({ 
     url: '/topics', 
     dataType: 'json', 
     type: 'GET', 
     success: getTopicJSON_Success, 
     error: getJSON_Error 
    }); 
} 
相關問題