2016-03-23 13 views
0

モジュールの内部でフォームを参照する方法を理解しようとしています。モジュール内部から特定のフォーム要素を参照する

モジュールは、次のようになります。

const UserShows = (function(){ 

    const saveShowToDashboard = function(evt) { 
    evt.preventDefault(); 
    const $saveShowForm = $(this); 
    setTimeout(function() { 
     $saveShowForm.children('.save-show-btn').val('Saved'); 
    }, 500); 
    const showInfo = $(this).children('.save-show-checkbox').val(); 
    const parsedShowInfo = JSON.parse(showInfo); 
    const _csrf = $(this).children('.csrf').val(); 
    const artistName = parsedShowInfo.artist; 
    const data = { 
     showInfo: parsedShowInfo, 
     _csrf: _csrf, 
    }; 
    console.log(data); 
    $.post('/artists/' + artistName, data, function(res) { 
     if (res === '/login') { 
     window.location = res; 
     }else{ 
     console.log(res); 
     } 
    }); 
    }; 

    return { 
    callSaveShowToDashboard: function(evt){ 
     return saveShowToDashboard(evt); 
    } 
    } 

})(); 

// Call saveShowToDashboard on click 
$('.save-show').on('submit', UserShows.callSaveShowToDashboard); 

私がいる問題は、私が提出されています特定のセーブ・ショーフォームを参照する方法を見つけ出すことができないということである(上のいくつかがあります各ページはアーティストのツアー日に対応しています)。

この関数をUserShowsモジュールの中に入れる前に、$(this)を使って特定のフォームを参照することができましたが、フォームはもはや関数の直接呼び出し元ではないため、作業。

答えて

0

JQueryでは、event.targetを使用してイベントをトリガーした要素を参照できます。ですから、このようなコードを書き直すと、それは動作します:

const saveShowToDashboard = function(evt) { 
    evt.preventDefault(); 
    const $saveShowForm = $(event.target); 
    setTimeout(function() { 
     $saveShowForm.children('.save-show-btn').val('Saved'); 
    }, 500); 
    const showInfo = $saveShowForm.children('.save-show-checkbox').val(); 
    const parsedShowInfo = JSON.parse(showInfo); 
    const _csrf = $saveShowForm.children('.csrf').val(); 
    const artistName = parsedShowInfo.artist; 
    const data = { 
     showInfo: parsedShowInfo, 
     _csrf: _csrf, 
    }; 
    console.log(data); 
    $.post('/artists/' + artistName, data, function(res) { 
     if (res === '/login') { 
     window.location = res; 
     }else{ 
     console.log(res); 
     } 
    }); 
    }; 
関連する問題