Logic in customizing timer in java script - javascript

I have an pop up dialog that appears after every one minute and in that pop up, I have a timer that count it's time starting from 1 minute, till 0. If user presses yes in the popup dialog, the modalpop is again reset to call again after one minute.
My problem is that it was working fine until I have not introduced startBackCountDown() which creates a timer inside that modal popup. Can somebody please help me. I am stucked here.
var mins = 1;
var secs = 0;
var timer;
//240000-Four minutes
// 120000- two minutes
//60000-OneMinute
var myVar = setInterval(function () { myTimer() }, 60000);
function myTimer() {
startBackCountDown();
$("#dialog").dialog("open");
}
function startBackCountDown() {
timer = setInterval('update()', 1000);
}
function update() {
var timeField = document.getElementById('Showtime');
if (secs == 0) {
if (mins == 0) {
timeField.innerHTML = "Time's up!";
clearInterval(timer);
//alert("Time's up");
return;
}
mins--;
secs = 59;
} else {
secs--;
}
if (secs < 10) {
timeField.innerHTML = 'Time left: ' + mins + ':0' + secs;
} else {
timeField.innerHTML = 'Time left: ' + mins + ':' + secs;
}
}
function ClearTimerValues() {
window.clearInterval(myVar);
clearInterval(timer);
}
function SetTimerValuesAgain() {
var client_Name = '#Session["ClientFullName"]';
var Client_Id = '#Session["Client_LoginID"]';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../Account/ResetUser",
data: "{'User_ID':'" + Client_Id + "','Client_Name':'" + client_Name + "'}",
dataType: "json",
success: function (data) {
if (data.Data == '1') {
myVar = setInterval(function () { myTimer() }, 60000);
//window.clearInterval(timer);
mins = 1;
secs = 0;
}
else {
window.clearInterval(myVar);
window.location = "/Account/login";
}
},
error: function (xhr) {
}
});
}
$(function () {
$("#dialog").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: false,
show: "blind",
hide: "blind",
buttons: {
"Yes": function () {
SetTimerValuesAgain();
$(this).dialog("close");
},
"No": function () {
ClearTimerValues();
$(this).dialog("close");
}
}
});
});

Related

How to run a function that a on form submit ajax with automatic click button

I am trying to submit a form with just automatic click button.
so I have a timer which is if the timer is already 0, it should submit the form automatically.
here is the code that I have.
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if (sec < 10) {
sec = '0' + sec;
}
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
//boolean is false
if (secondsRemaining === 0) {
submitAnswer();
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
function submitAnswer() {
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
method: "post",
url: url,
data: new FormData(this),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
});
}
How can I run the submitAnswer function if the timer is already 0. any help would be really appreciated.
The submitAnswer() function just attaches the event handler, it doesn't actually submit the form.
To achieve what you require attach the submit event handler when the page loads, then when you want to submit the form trigger that event on it. Try this:
// attach submit event handler when the page loads
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
// ajax settings here...
});
});
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = ('00' + (secondsRemaining - (min * 60))).slice(-2); // note tidied the logic here
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
// stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
if (secondsRemaining === 0) {
$('#form_question_scenario').trigger('submit'); // submit the form here
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
You don't need submit event at all, just call the function like you did when 0 sec is left, get id of form and create new form data, and do Ajax request...
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
$.ajax({
method: "post",
url: url,
data: new FormData(myForm),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
EXAMPLE:
Form data is populated without submit event just by calling the function:
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
let data = new FormData(myForm)
formObj = {};
for (var pair of data.entries()) {
formObj[pair[0]] = pair[1]
}
console.log(formObj)
}
submitAnswer()
<form id="form_question_scenario">
<input type="text" value="test" name="test">
</form>

set and clear interval by ajax

I simply want to clear previous interval and set a new one when an ajax call is made.
The current code is:
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: {
'title': title
},
dataType: 'json',
success: function (data) {
var interval = null;
if(data.count_down){
var _second = 1000;
var _minute = _second * 60;
var timer;
var end = data.count_down
mins = Math.floor(end / 60);
secs = end % 60;
var interval = setInterval(count,1000)
function count(){
console.log(parseInt(secs))
secs -= 1
}}
else{
var stop = function(){
clearInterval(interval);}
}
}
})
})
I tryed many recommended variations to be able to clear the interval from outside of the function. Such as;
setting the "interval" variable to null or to false,
window.setInterval,
writing the count function inside of setInterval,
writing the count function as a separate function outside of the ajax function,
But neither of the variations cleared the interval.
Later on I'll also need to clear the interval on keydown.
From your code, I will do like below (P.S. didn't test):
var interval = null,
secs = 0;
function count() {
console.log(secs);
secs -= 1;
}
function deal_data(data) {
if(interval == null && data.count_down){
var end = data.count_down
secs = end % 60;
interval = setInterval(count, 1000);
else if (interval != null) {
clearInterval(interval);
}
}
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: { 'title': title },
dataType: 'json',
success: function (data) {
deal_data(data);
}
})
})
After several changes to MarshalSHI's answer the code ended up like this:
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: { 'title': title },
dataType: 'json',
success: function (data) {
deal_data(data);
}
})
})
var interval = null;
function deal_data(data) {
if(interval == null && data.count_down){
var end = data.count_down
secs = end % 60;
interval = setInterval(count, 1000);}
else if (interval != null) {
clearInterval(interval);
interval = null;
}
}
function count() {
console.log(secs);
secs -= 1;
}

stop the timer function from executing when form is submitted

I have an online quiz program where user needs to complete it within a time period. When user runs out of time,I show an alert saying that your time is up and he is redirected to result page. I get the same alert when user completes the quiz before the time expires and is inside result page. I have modified the code like following but its not working. I am calling the function initTimer(1,1) inside an ajax requested page named questions.php.
In index.php
function initTimer(periodInSeconds, status) {
if (status == 0) {
return false;
}
var end = Date.now() + periodInSeconds * 1000 * 60;
var x = window.setInterval(function() {
var timeLeft = Math.floor((end - Date.now()) / 1000);
if (timeLeft < 0) {
clearInterval(x);
alert("Time's Up!");
timeExpired = true;
var completed = 1;
$.ajax({
type: "POST",
url: "success.php",
data: {
'userID': <?php echo $_SESSION['userID'];?>
},
success: function(hasil) {
$('.response_div').html(hasil);
}
});
}
$(document).find('#timerspan').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
}, 200);
}
//when user submits the form before time expires
$(document).on('submit', '.form_choice', function() {
initTimer(1, 0)
$.ajax({
type: "POST",
url: "result.php",
data: data,
success: function(hasil) {
$('.response_div').html(hasil);
}
})
});
I dont want the init function() to execute when user submits the form before time expires.Please help me
Declare the variable holding the timer outside the initTimer function, then you can clear the timer by calling it with status = 0
var timer;
function initTimer(periodInSeconds, status) {
if (status == 0) {
clearInterval(timer);
return;
}
var end = Date.now() + periodInSeconds * 1000 * 60;
timer = window.setInterval(function() {
var timeLeft = Math.floor((end - Date.now()) / 1000);
if (timeLeft < 0) {
clearInterval(timer);
alert("Time's Up!");
timeExpired = true;
var completed = 1;
$.ajax({
type: "POST",
url: "success.php",
data: {
'userID': <?php echo $_SESSION['userID'];?>
},
success: function(hasil) {
$('.response_div').html(hasil);
}
});
}
$(document).find('#timerspan').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
}, 200);
}
//when user submits the form before time expires
$(document).on('submit', '.form_choice', function() {
initTimer(1, 0)
$.ajax({
type: "POST",
url: "result.php",
data: data,
success: function(hasil) {
$('.response_div').html(hasil);
}
})
});

clearInterval not working | undefined

I have such jQuery code and have problem with clearing intervals.
var secs = 50, width = 100;
var counter = function() {
if(secs > 0) {
secs--;
width = width - 2;
$('#time').css('width', width + '%').attr('aria-valuenow', width);
$('.seconds').html(secs);
} else if(secs == 0){
$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
clearInterval(counter);
setInterval(winner, 3000);
}
};
var winner = function() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "game_results"
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "you") {
$('.waiting').addClass('hidden');
$('.you').removeClass('hidden');
} else if (data == "opponent") {
$('.waiting').addClass('hidden');
$('.opponent').removeClass('hidden');
}
}
});
console.log(clearInterval(winner)); // heer
}
function answer(question_id, answer, question) {
var question_higher = question_id + 1;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "play",
answer: answer,
question: question
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "wrong") {
$.playSound('build/sounds/wrong');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-danger');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
} else if (data == "correct") {
$.playSound('build/sounds/correct');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-success');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
}
}
});
if(question_id == 5) {
clearInterval(counter);
setTimeout(function() {
//$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
}, 750);
setInterval(winner, 3000);
}
}
$(document).ready(function() {
$('*[data-question="1"]').removeClass('hidden');
setInterval(counter, 1000);
});
Im trying to get this work for almost 5 hours without results.
Both clearInterval(counter); and clearInterval(winner) are not working and flooding my server with requets.
Thanks in advance for any help.
Let's see how you're clearing the interval.
clearInterval(winner)
where, winner is the function. To clear the interval, the ID of the interval should be passed as parameter.
When setting the interval, catch the interval ID in a variable
winnerInterval = setInterval(winner, 3000);
and use this variable to clear interval.
clearInterval(winnerInterval);
Make sure the variable containing interval ID is in the scope when clearing the interval.
See clearInterval.

Jquery Plugin. Options for each instances

I've created a jquery plugin that is called several times inside the same page. Each time I call the plugin I pass differents parameters and a callback function that returns the ID of the element, that it's passed as parameter but I always receive the ID of the last element that has been applied the plugin.
I always thought that everytime I call a plugin a new instance is generated.
This is my plugin code:
(function ($) {
$.audioRecorder = {
constants: {
},
options: {
domain: "http://example.com",
storageUrl: "/services/uploader/uploadtoazure",
storageUrlIOSDevice: "/services/uploader/uploadaudiofromiosdevice",
storageAudioContainer: null,
storageAudioPath: null,
storageMimeType: "audio/mpeg",
storageExtension: "mp3",
container: null,
handlerInterval: null,
callbackAudioSaved: null,
callbackPlay: null,
callbackStop: null,
id: null
},
methods: {
init: function (options) {
$.extend(true, $.audioRecorder.options, options);
window.microm = new Microm();
$.audioRecorder.options.container = $(this);
$.audioRecorder.methods.build();
$.audioRecorder.methods.bind();
},
build: function () {
var template = $.audioRecorder.templates.recorder.replace(/##domain##/g, $.audioRecorder.options.domain.replace('https','http'));
$.audioRecorder.options.container.html(template);
$.audioRecorder.methods.showRecordButton();
if ($.audioRecorder.methods.isIOSDevice()) {
$.audioRecorder.options.container.find(".audio-recorder-timer").hide();
}
},
bind: function () {
$.audioRecorder.options.container.find(".audio-recorder-record").click($.audioRecorder.methods.record);
$.audioRecorder.options.container.find(".audio-recorder-stop").click($.audioRecorder.methods.stop);
$.audioRecorder.options.container.find(".audio-recorder-uploader").change($.audioRecorder.methods.saveAudioFromFileUpload);
},
record: function () {
if ($.audioRecorder.methods.isIOSDevice()) {
$.audioRecorder.options.container.find(".audio-recorder-uploader").click();
}
else {
microm.record().then(function () {
$.audioRecorder.methods.initTimer();
$.audioRecorder.methods.showStopButton();
console.log('Recording...');
}).catch(function (error) {
console.log('error recording', error);
});
}
},
stop: function () {
$.audioRecorder.methods.stopTimer();
$.audioRecorder.methods.showLoading();
microm.stop().then(function (mp3) {
$.audioRecorder.methods.saveAudio(mp3);
console.log('Stop record');
});
},
saveAudio: function (mp3) {
var fd = new FormData();
fd.append('data', mp3.blob);
fd.append('container', $.audioRecorder.options.storageAudioContainer);
fd.append('path', $.audioRecorder.options.storageAudioPath);
fd.append('extension', $.audioRecorder.options.storageExtension);
fd.append('mimeType', $.audioRecorder.options.storageMimeType);
$.ajax({
url: $.audioRecorder.options.domain + $.audioRecorder.options.storageUrl,
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (url) {
$.audioRecorder.methods.audioSaved(url);
},
error: function () {
$.audioRecorder.methods.showRecordButton();
}
});
},
saveAudioFromFileUpload: function () {
if ($.audioRecorder.options.container.find(".audio-recorder-uploader")[0].files == null || $.audioRecorder.options.container.find(".audio-recorder-uploader")[0].files.length == 0) {
return;
}
$.audioRecorder.methods.showLoading();
var file = $.audioRecorder.options.container.find(".audio-recorder-uploader")[0].files[0];
var fd = new FormData();
fd.append('data', file);
fd.append('container', $.audioRecorder.options.storageAudioContainer);
fd.append('path', $.audioRecorder.options.storageAudioPath);
fd.append('mimeType', $.audioRecorder.options.storageMimeType);
$.ajax({
url: $.audioRecorder.options.domain + $.audioRecorder.options.storageUrlIOSDevice,
type: 'post',
data: fd,
processData: false,
contentType: false,
success: function (data) {
$.audioRecorder.methods.audioSaved(data.url, data.duration);
},
error: function () {
$.audioRecorder.methods.showRecordButton();
}
});
},
audioSaved: function (url, duration) {
$.audioRecorder.methods.showRecordButton();
var timer = $.audioRecorder.methods.getTimer();
$.audioRecorder.methods.resetTimer();
if (duration != null) {
var seconds = duration % 60;
var minutes = Math.floor(duration / 60);
timer = minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
var template = $.audioRecorder.templates.player;
template = template.replace(/##link##/g, url);
template = template.replace(/##length##/g, timer);
template = template.replace(/##domain##/g, $.audioRecorder.options.domain.replace('https','http'));
if ($.audioRecorder.options.callbackPlay != null) {
template = template.replace(/##callbackPlay##/g, $.audioRecorder.options.callbackPlay.name + "(event)");
}
else {
template = template.replace(/##callbackPlay##/g, "");
}
if ($.audioRecorder.options.callbackStop != null) {
template = template.replace(/##callbackStop##/g, $.audioRecorder.options.callbackStop.name + "(event)");
}
else {
template = template.replace(/##callbackStop##/g, "");
}
if ($.audioRecorder.options.callbackAudioSaved != null) {
$.audioRecorder.options.callbackAudioSaved(url, template, $.audioRecorder.options.container);
}
else {
$.audioRecorder.options.container.append(template);
}
},
initTimer: function () {
$.audioRecorder.methods.resetTimer();
$.audioRecorder.options.handlerInterval = setInterval($.audioRecorder.methods.addSecondToTimer, 1000);
},
resetTimer: function () {
$.audioRecorder.options.container.find(".audio-recorder-timer").text("0:00");
},
addSecondToTimer: function () {
var timerText = $.audioRecorder.options.container.find(".audio-recorder-timer").text().split(":");
var minutes = parseInt(timerText[0]);
var seconds = parseInt(timerText[1]);
seconds++;
if (seconds >= 60) {
minutes++;
seconds = 0;
}
timerText = minutes + ":" + (seconds < 10 ? "0" + seconds : seconds);
$.audioRecorder.options.container.find(".audio-recorder-timer").text(timerText);
},
stopTimer: function () {
clearInterval($.audioRecorder.options.handlerInterval);
},
getTimer: function () {
return $.audioRecorder.options.container.find(".audio-recorder-timer").text();
},
getSecondsTimer: function () {
var timerText = $.audioRecorder.options.container.find(".audio-recorder-timer").text().split(":");
var minutes = parseInt(timerText[0]);
var seconds = parseInt(timerText[1]);
return minutes * 60 + seconds;
},
showRecordButton: function () {
$.audioRecorder.options.container.find(".audio-recorder-record").show();
$.audioRecorder.options.container.find(".audio-recorder-stop").hide();
$.audioRecorder.options.container.find(".audio-recorder-loading").hide();
},
showStopButton: function () {
$.audioRecorder.options.container.find(".audio-recorder-record").hide();
$.audioRecorder.options.container.find(".audio-recorder-stop").show();
$.audioRecorder.options.container.find(".audio-recorder-loading").hide();
},
showLoading: function () {
$.audioRecorder.options.container.find(".audio-recorder-record").hide();
$.audioRecorder.options.container.find(".audio-recorder-stop").hide();
$.audioRecorder.options.container.find(".audio-recorder-loading").show();
},
playerPlay: function (event) {
event.stopPropagation();
event.preventDefault();
var player = $(event.target).closest('.audio-recorder-player');
player.find('audio')[0].play();
$.audioRecorder.methods.stopPlayerTimer(player);
$.audioRecorder.methods.initPlayerTimer(player);
$.audioRecorder.methods.showPlayerStopButton(player);
},
playerStop: function (event) {
event.stopPropagation();
event.preventDefault();
var player = $(event.target).closest('.audio-recorder-player');
player.find('audio')[0].pause();
player.find('audio')[0].currentTime = 0;
$.audioRecorder.methods.stopPlayerTimer(player);
$.audioRecorder.methods.resetPlayerTimer(player);
$.audioRecorder.methods.showPlayerPlayButton(player);
},
initPlayerTimer: function (player) {
$.audioRecorder.methods.resetPlayerTimer(player);
player.prop("interval", setInterval(function () { $.audioRecorder.methods.addSecondToPlayerTimer(player); }, 1000));
},
resetPlayerTimer: function (player) {
player.find(".audio-recorder-player-current-seek").text("0:00");
player.find(".audio-recorder-player-progress-bar").width(0);
},
addSecondToPlayerTimer: function (player) {
if (player.find(".audio-recorder-player-current-seek").text() == player.find(".audio-recorder-player-total-time").text()) {
$.audioRecorder.methods.stopPlayerTimer(player);
$.audioRecorder.methods.showPlayerPlayButton(player);
return;
}
var timerText = player.find(".audio-recorder-player-current-seek").text().split(":");
var minutes = parseInt(timerText[0]);
var seconds = parseInt(timerText[1]);
seconds++;
if (seconds >= 60) {
minutes++;
seconds = 0;
}
timerText = minutes + ":" + (seconds < 10 ? "0" + seconds : seconds);
player.find(".audio-recorder-player-current-seek").text(timerText);
// Progress bar
var currentSecons = $.audioRecorder.methods.getSecondsPlayerTimer(player);
var totalSecons = $.audioRecorder.methods.getSecondsTotalPlayerTimer(player);
var progress = parseFloat(currentSecons) / parseFloat(totalSecons);
var totalWidth = player.find(".audio-recorder-player-progress-bar-parent").width();
player.find(".audio-recorder-player-progress-bar").width(progress * totalWidth);
},
stopPlayerTimer: function (player) {
clearInterval(player.prop("interval"));
},
getSecondsPlayerTimer: function (player) {
var timerText = player.find(".audio-recorder-player-current-seek").text().split(":");
var minutes = parseInt(timerText[0]);
var seconds = parseInt(timerText[1]);
return minutes * 60 + seconds;
},
getSecondsTotalPlayerTimer: function (player) {
var timerText = player.find(".audio-recorder-player-total-time").text().split(":");
var minutes = parseInt(timerText[0]);
var seconds = parseInt(timerText[1]);
return minutes * 60 + seconds;
},
showPlayerPlayButton: function (player) {
player.find(".audio-recorder-player-play").show();
player.find(".audio-recorder-player-stop").hide();
},
showPlayerStopButton: function (player) {
player.find(".audio-recorder-player-play").hide();
player.find(".audio-recorder-player-stop").show();
},
isIOSDevice() {
return navigator.platform != null && ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
}
},
templates: {
recorder: "<img src='##domain##/images/audiorecorder/audio-recorder-record.png' class='audio-recorder-record' style='float: left;' title='Grabar archivo de sonido' />" +
"<img src='##domain##/images/audiorecorder/audio-recorder-stop.png' class='audio-recorder-stop' style='float: left;' title='Detener grabacion' />" +
//"<img src='##domain##/images/audiorecorder/audio-recorder-loading.gif' class='audio-recorder-loading' style='float: left;' />" +
"<span class='audio-recorder-loading' style='float: left; font-size: 12px; width: 48px; overflow: hidden; margin-top: 18px;'>Cargando...</span>" +
"<span class='audio-recorder-timer' style='float: left; margin-top: 12px; font-size: 25px; margin-left: 10px;'>0:00</span>" +
"<input type='file' class='audio-recorder-uploader' style='display: none;' accept='audio/*;capture=microphone' />",
player: "<div class='audio-recorder-player'>" +
"<a href='##link##' target='_blank' style='float: left;'>" +
"<img src='##domain##/images/audiorecorder/audio-recorder-play.png' class='audio-recorder-player-play' style='float: left;' onclick='$.audioRecorder.methods.playerPlay(event); ##callbackPlay##' title='Reproducir audio' />" +
"<img src='##domain##/images/audiorecorder/audio-recorder-stop.png' class='audio-recorder-player-stop' style='display: none; float: left;' onclick='$.audioRecorder.methods.playerStop(event); ##callbackStop##' title='Detener audio' />" +
"</a>" +
"<audio src='##link##'></audio>" +
"<span class='audio-recorder-player-current-seek' style='float: left; margin-top: 17px; margin-left: 10px;'>0:00</span>" +
"<div class='audio-recorder-player-progress-bar-parent' style='float: left; margin-top: 14px; margin-left: 3px; width: 204px; height: 22px; box-sizing: border-box; border: 1px solid #AAA; padding: 1px; background-color: #FFF;'>" +
"<div class='audio-recorder-player-progress-bar' style='float: left; height: 18px; background-color: #BCD100;font-size:1px'> </div>" +
"</div>" +
"<span class='audio-recorder-player-total-time' style='float: left; margin-top: 17px; margin-left: 3px;'>##length##</span>" +
"</div>"
}
}
// Privates
//
$.fn.audioRecorder = function (method) {
if ($.audioRecorder.methods[method]) {
return $.audioRecorder.methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return $.audioRecorder.methods.init.apply(this, arguments);
} else {
$.error(method + ' no definido en noteges.audio-recorder.js');
}
};
})(jQuery);
And I call the plugin this way;
$("#" + ID1).audioRecorder({
domain: 'https://example.com',
storageUrl: "/services/uploader/uploadtoazure",
storageAudioContainer: self.azureContainer,
storageAudioPath: self.azureContainerAudio,
callbackAudioSaved: audioSaved,
callbackPlay: null,
id: audioID
});
$("#" + ID2).audioRecorder({
domain: 'https://example.com',
storageUrl: "/services/uploader/uploadtoazure",
storageAudioContainer: self.azureContainer,
storageAudioPath: self.azureContainerAudio,
callbackAudioSaved: audioSaved,
callbackPlay: null,
id: audioID
});
I always thought that everytime I call a plugin a new instance is
generated.
Your plugin function has the context of a new jQuery object instance, but $.audioOptions is not part of that. It is a property on the jQuery global object so a new one isn't created each time the plugin function is called. You can tell this because you keep having to use $.audioOptions.methods to call a method instead of a method call like this.record()
You can refactor your code to create a new object, or a new instance (if changing it to a constructor function), each time the plugin is called. Then you can save the options on the new object/instance, call methods from the it, etc.
Note you could place your methods on the jQuery object instance but that would be polluting it and possibly overwriting jQuery methods.
$.audioRecorder = {
/* other code */
methods: {
init:function(options,$element){
this.options = $.extend(true,{},$.audioRecorder.options,options);
this.options.container = $element;
this.bind();
},
bind: function () {
//uses arrow function to help maintain context and for less code,
//change if supporting older browsers
this.options.container.find(".audio-recorder-record").click(e=>this.record());
}
}
};
$.fn.audioRecorder = function(options){
//if only supposed to use a single element
//otherwise use code in a this.each() callback
var $element = this.first();
var arInstance = Object.create($.audioRecorder.methods);
arInstance.init(options,$element);
$element.data("audioRecorder",arInstance);
return this;
};
Demo
(function($){
$.audioRecorder = {
options:{},
methods: {
init:function(options,$element){
this.options = $.extend(true,{},$.audioRecorder.options,options);
this.options.container = $element;
this.build();
this.bind();
},
build:function(){
this.options.container.append( $.audioRecorder.templates.aTemplate );
},
bind: function () {
this.options.container.find("button").click(e=>this.record());
},
record:function(){
console.log("Record called for id: "+this.options.id);
}
},
templates:{
aTemplate:"<button>Hit to record</button>"
}
};
$.fn.audioRecorder = function(options){
var $element = this.first();
var arInstance = Object.create($.audioRecorder.methods);
arInstance.init(options,$element);
$element.data("audioRecorder",arInstance);
return this;
};
})(jQuery);
jQuery("#container").audioRecorder({
id:"firstRecorder"
});
jQuery("#container1").audioRecorder({
id:"secondRecorder"
});
jQuery("#container2").audioRecorder({
id:"thirdRecorder"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<div id="container1"></div>
<div id="container2"></div>

Categories

Resources