2014-10-20 43 views
2

這是我main.js文件:如何讓JS Turbolinks友好?

jQuery(function($) { 
    $('LI.tree-item-name').has('ul').click(function() { 
    if ($(this).hasClass('opened')) { 
     $(this).find('UL').slideUp(); 
     $(this).removeClass('opened'); 
    } else { 
     $(this).find('UL').slideDown(); 
     $(this).addClass('opened'); 
    } 
    return false; 
    }); 

    $('LI.tree-item-name li').click(function(e) { 
    e.stopPropagation(); 
    }) 
}); 

jQuery(window).load(function(){ 
    jQuery('#video').removeClass('loading'); 
    jQuery('#video .box').animate({'opacity' : '1'}); 
    var $container = jQuery('#video'); 
    $container.masonry({ 
     columnWidth: 299, 
     itemSelector: '.box' 
    }); 
    jQuery('.popupbox').click(function(){ 
     jQuery('.popup:visible').fadeOut(); 
     var id = '#'+jQuery(this).data('popup'); 
     jQuery('#overlay').fadeIn(); 
     jQuery(id).css('top', jQuery(window).height()/2 - jQuery(id).height()/2).fadeIn(); 
     return false; 
    }); 
    jQuery('.profile_popupbox').click(function(){ 
     jQuery('.popup:visible').fadeOut(); 
     var id = '#'+jQuery(this).data('popup'); 
     jQuery('#overlay').fadeIn(); 
     jQuery(id).css({'top': "20px", 'left': "-200px"}).fadeIn();    
     return false; 
    }); 
    jQuery('#overlay').click(function(){ 
     jQuery('.popup:visible').fadeOut(); 
     jQuery(this).fadeOut(); 
    }); 
}); 

我會爲這愛是Turbolinks友好。

我試着這樣做:

var ready; 
ready = jQuery(window).load(function(){ 
    jQuery('#video').removeClass('loading'); 
    jQuery('#video .box').animate({'opacity' : '1'}); 
    var $container = jQuery('#video'); 
    $container.masonry({ 
     columnWidth: 299, 
     itemSelector: '.box' 
    }); 
    jQuery('.popupbox').click(function(){ 
     jQuery('.popup:visible').fadeOut(); 
     var id = '#'+jQuery(this).data('popup'); 
     jQuery('#overlay').fadeIn(); 
     jQuery(id).css('top', jQuery(window).height()/2 - jQuery(id).height()/2).fadeIn(); 
     return false; 
    }); 
    jQuery('.profile_popupbox').click(function(){ 
     jQuery('.popup:visible').fadeOut(); 
     var id = '#'+jQuery(this).data('popup'); 
     jQuery('#overlay').fadeIn(); 
     // jQuery(id).css('top', jQuery(window).height() - jQuery(id).height()/2).fadeIn(); 
     jQuery(id).css({'top': "20px", 'left': "-200px"}).fadeIn();    
     return false; 
    }); 
    jQuery('#overlay').click(function(){ 
     jQuery('.popup:visible').fadeOut(); 
     jQuery(this).fadeOut(); 
    }); 
}); 

$(document).ready(ready); 
$(document).on('page:load', ready); 

這並沒有工作,也沒有讓這兩個功能Turbolinks友好。

所以我想讓整個文件TL友好。

編輯1

我也有一個upload.js.erb它有這個,那個沒有得到頁面加載完成後執行:

$("#myVCModal").html("<%= escape_javascript(render 'videos/upload_video') %>"); 
$("#myModal").html("<%= escape_javascript(render 'videos/upload_video') %>"); 

$("#add-video-step-1").html("<%= escape_javascript(render 'videos/upload_video') %>"); 
$("#video-comment").html("<%= escape_javascript(render 'videos/upload_video') %>"); 
$('myModalPL').modal(show); 

Ladda.bind('button'); 

我想所有這些JS位在我應用程序返回工作。

編輯2

所以現在我有main.js東西的工作 - 感謝@ User089247。但是其他執行JS的模式根本不起作用......即,編輯1.根據代碼

正在發生的事情是我打這個上傳按鈕:

<%= link_to "<i class='fa fa-film fa-lg'></i> Upload".html_safe, "#", class: "upload popupbox", data: { popup: "add-video-step-1"} %> 

這是一個被炒魷魚的模式:

<div id="overlay">&nbsp;</div> 
<div class="popup" id="add-video-step-1"> 
    <div class="titles clearfix"> 
     <h2>Upload a Video</h2> 
     <p><i>Step 1 of 2 - TEST</i></p> 
    </div> 
    <div class="content"> 
    <% if @family_tree %> 
     <%= simple_form_for([@family_tree, @video], :remote => true) do |f| %> 
     <div class="column"> 
       <div class="f-row"> 
        <%= f.input :title, label: "Title:" %> 
       </div> 
       <div class="f-row"> 
        <%= f.input :description,label: "Description:" %> 
       </div> 
       <div class="f-row"> 
        <%= f.input :circa, as: :datepicker, start_year: Date.today.year - 5, label: "Circa:" %> 
       </div> 
       <div class="f-row"> 
        <label for="family">Family in this video:</label> 
        <%= f.collection_select :user_ids, @family_tree.members.order(:first_name), :id, :first_name, {}, {multiple: true} %> 
       </div> 
      </div> 
      <%= f.button :submit, "Add Video" %> 
     <% end %> 
     <% end %> 
    </div> <!-- //content --> 
</div> <!-- //popup --> 

然後當你點擊「添加視頻」 ,它應該帶你到第二模態這是這樣的:

<div class="bootstrap-styles"> 
<div class="modal-header"> 
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> 
    <h3 id="myModalLabel">Upload your Video</h3> 
    <p><i>Step 2 of 2 - TEST</i></p> 
    </div> 
    <div class="modal-body"> 
    <div class="form"> 
     <%= form_tag @upload_info[:url], :multipart => true do %> 
     <div>Step 2 of 2</div> 
     <%= hidden_field_tag :token, @upload_info[:token] %> 
     <%= file_field_tag :file, title: 'Choose video to upload' %> 
     <p class="uploader"> 
      <button class="btn btn-success ladda-button" data-color="green" data-style="expand-left"><span class="ladda-label">Upload Video</span><span class="ladda-spinner"></span></button> 
     </p> 
     <% end %> 

    </div> 
    </div> 
    <div class="modal-footer"> 
    </div> 
</div> 

我想問題是我沒有看到如何th是第二模態將執行,根據我的upload.js.erb或我錯過了什麼?

編輯3

這裏有一個服務器日誌的相關部分,當這個上傳視頻動作完成(截斷簡潔):

Started POST "/family_trees/1/videos" for 127.0.0.1 at 2014-10-28 02:16:48 -0500 
Processing by VideosController#create as JS 
    Parameters: {"utf8"=>"✓", "video"=>{"title"=>"Hello there", "description"=>"Why hello there lady", "circa"=>"", "user_ids"=>[""]}, "commit"=>"Add Video", "family_tree_id"=>"1"} 
    User Load (3.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1 
    FamilyTree Load (1.2ms) SELECT "family_trees".* FROM "family_trees" WHERE "family_trees"."user_id" = $1 LIMIT 1 [["user_id", 1]] 
    ReadMark Load (1.0ms) SELECT "read_marks".* FROM "read_marks" WHERE "read_marks"."user_id" = $1 AND "read_marks"."readable_type" = 'PublicActivity::ORM::ActiveRecord::Activity' AND "read_marks"."readable_id" IS NULL ORDER BY "read_marks"."id" ASC LIMIT 1 [["user_id", 1]] 
    FamilyTree Load (1.0ms) SELECT "family_trees".* FROM "family_trees" WHERE "family_trees"."id" = $1 LIMIT 1 [["id", 1]] 
    (1.2ms) SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL))) [["user_id", 1]] 
    Membership Load (1.7ms) SELECT "memberships".* FROM "memberships" WHERE "memberships"."user_id" = 1 AND "memberships"."family_tree_id" = 1 
    (3.6ms) BEGIN 
    SQL (3.4ms) INSERT INTO "videos" ("created_at", "description", "title", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", "2014-10-28 07:16:48.340452"], ["description", "Why hello there lady"], ["title", "Hello there"], ["updated_at", "2014-10-28 07:16:48.340452"]] 
    (4.5ms) COMMIT 
Redirected to http://localhost:3000/ 
Completed 302 Found in 40ms (ActiveRecord: 20.6ms) 

Started GET "/" for 127.0.0.1 at 2014-10-28 02:16:48 -0500 
    User Load (4.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1 
Processing by DashboardController#index as JS 

對於它的價值,即使它成功完成處理這個GET "/"請求,它實際上不會重新加載/重定向瀏覽器。它只停留在模態。

錯誤的JS控制檯說:

Failed to load resource: net::ERR_CACHE_MISS 

這裏是VideoController#Create

def create 
    authorize! :read, @family_tree 
    @video = Video.new(video_params) 

    respond_to do |format| 
     if @video.save 
     format.html { redirect_to root_path } 
     format.json { render action: 'show', status: :created, location: @video } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @video.errors, status: :unprocessable_entity } 
     end 
    end 
+0

您是否嘗試過使用https://rubygems.org/gems/jquery-turbolinks?它帶回默認事件。 – bodrovis 2014-10-20 08:47:05

+0

是的,我正在使用它。然而,我仍然有這個代碼塊的問題。特別是當我點擊很多頁面並返回到主頁面時,這行代碼在執行時不會執行:'jQuery('#video .box')。animate({'opacity':'1'});' - 所以我想象整個功能沒有被執行。 – marcamillion 2014-10-20 08:51:12

+0

那到底發生了什麼?是第二個模式彈出或不?你看到任何JavaScript/jQuery錯誤或rails服務器日誌中的任何錯誤? – Surya 2014-10-27 12:33:38

回答

3

改變你的主。JS這個(我喜歡這種方式,因爲它是很容易調試jQuery中的問題,而在方法網迷路,和它的作品真的很好用turbolinks無需增加jquery-turbolinks寶石吧):

$(document).on("page:change", function(){ 
    MainJS.init(); 
}); 

MainJS = { 
    init: function() { 
    MainJS.initializePage(); 
    $('.popupbox').on('click', MainJS.popupBox); 
    $('.profile_popupbox').on('click', MainJS.profilePopupbox); 
    $('#overlay').on('click', MainJS.overLay); 
    $('LI.tree-item-name').has('ul').on('click', MainJS.treeItemName); 

    $('LI.tree-item-name li').on('click', function(ev) { 
     ev.stopPropagation(); 
    }); 
    }, 

    initializePage: function(){ 
    $('#video').removeClass('loading'); 
    $('#video .box').animate({'opacity' : '1'}); 
    var $container = $('#video'); 
    $container.masonry({ 
     columnWidth: 299, 
     itemSelector: '.box' 
    }); 
    }, 

    popupBox: function(){ 
    $('.popup:visible').fadeOut(); 
    var id = '#'+$(this).data('popup'); 
    $('#overlay').fadeIn(); 
    $(id).css('top', $(window).height()/2 - $(id).height()/2).fadeIn(); 
    return false; 
    }, 

    profilePopupbox: function(){ 
    $('.popup:visible').fadeOut(); 
    var id = '#'+$(this).data('popup'); 
    $('#overlay').fadeIn(); 
    // $(id).css('top', $(window).height() - $(id).height()/2).fadeIn(); 
    $(id).css({'top': "20px", 'left': "-200px"}).fadeIn();    
    return false; 
    }, 

    overLay: function(){ 
    $('.popup:visible').fadeOut(); 
    $(this).fadeOut(); 
    }, 

    treeItemName: function(){ 
    if ($(this).hasClass('opened')) { 
     $(this).find('UL').slideUp(); 
     $(this).removeClass('opened'); 
    } else { 
     $(this).find('UL').slideDown(); 
     $(this).addClass('opened'); 
    } 
    return false; 
    } 
} 

現在,如果你可以很容易地調試上面的代碼,看看哪部分工作/不工作,例如:

$(document).on("page:change", function(){ 
    MainJS.init(); 
    console.log('MainJS.init() was called successfully); 
}); 

或:

MainJS = { 
    init: function() { 
    MainJS.initializePage(); 
    $('.popupbox').on('click', MainJS.popupBox); 
    $('.profile_popupbox').on('click', MainJS.profilePopupbox); 
    $('#overlay').on('click', MainJS.overLay); 
    console.log('MainJS initialization was successful.'); 
    }, 

等。你明白了吧?

關於你upload.js.erb問題,我不知道什麼是錯在那裏,它應該工作(如同樣的事情對我的作品),但是,您可以繞到代碼:$(document).on("page:change", function(){,看它是否作品,但我懷疑這不是問題。

+0

謝謝你。給出你的答案,這是否意味着我不需要'jQuery.turbolinks'寶石?只是問,因爲我正在使用它。 – marcamillion 2014-10-27 10:15:19

+0

老實說,我從未在我的Rails 4應用程序中使用jquery-turbolinks gem。我使用的是我在回答中提出的相同方法,我不確定你有什麼目的,但爲了更安全一方,可以將它保存在應用程序中,稍後將其刪除,並查看是否有任何依賴工作和承諾您的遠程git回購。 – Surya 2014-10-27 10:20:21

+0

啊,好的。這就說得通了。你遺漏了一塊JS代碼,這是最重要的部分:$('LI.tree-item-name')。has('ul')。click(function(){'。轉換該部分到這個新的結構?對不起,JS noob:| – marcamillion 2014-10-27 10:21:57