jquery - Re-using JavaScript Method -
i have these 2 methods pretty much same thing. improve re-using other method, method overriding in object oriented programming.
method 1 summary: based on level
, create post
request servlet returns courses particular level in json format (response
). load these courses combo box ($loadto
). after pre-select course
provided , show modal.
function loadcoursesbylevelthenset(level, course, $loadto) { $.post( ... , ... , function(response) { var options = '<option value="">please select course...</option>'; (var = 0; < response.length; i++) { ... } $loadto.html(options); $loadto.val(course); $('#modal').modal('show'); }).fail(function() { alert('something went wrong while loading options courses. please seek again.'); }); }
method 2 summary: based on level
, create post
request servlet returns courses particular level
in json format (response
), load these courses combo box ($loadto
).
function loadcoursesbylevel(level, $loadto) { $.post( ... , ... , function(response) { var options = '<option value="">please select course...</option>'; (var = 0; < response.length; i++) { ... } $loadto.html(options); }).fail(function() { alert('something went wrong while loading options courses. please seek again.'); }); }
this came up, doesn't work correctly:
function loadcoursesbylevelthenset(level, course, $loadto) { if (loadcoursesbylevel(level, $loadto) === true) { //after courses loaded //select course of study //and show modal $loadto.val(course); $('#modal').modal('show'); } } function loadcoursesbylevel(level, $loadto) { $.post( ... , ... , function(response) { var options = '<option value="">please select course...</option>'; (var = 0; < response.length; i++) { ... } $loadto.html(options); }).fail(function() { alert('something went wrong while loading options courses. please seek again.'); }).done(function() { homecoming true; }); }
what doing wrong? there way accomplish this? give thanks you.
the problem attempted solution can't homecoming value because ajax asynchronous.
you pass callback loadcoursesbylevel()
, , have run after runs own success code. checking if callback undefined, can create optional more flexibility.
function loadcoursesbylevel(level, $loadto, callback) { $.post( ... , ... , function(response) { var options = '<option value="">please select course...</option>'; (var = 0; < response.length; i++) { options += '<option value="' + response[i].code + '">' + response[i].course + '</option>'; } $loadto.html(options); if(typeof callback != 'undefined'){ callback(); // <------------- execute callback } }).fail(function() { alert('something went wrong while loading options courses. please seek again.'); }); } function loadcoursesbylevelthenset(level, course, $loadto) { loadcoursesbylevel(level, $loadto, function() { $loadto.val(course); $('#modal').modal('show'); }); }
javascript jquery
No comments:
Post a Comment