Variable Scope help: this.reset() is not a function - javascript

when save() executes this.reset() or that.reset() it can't find the reset() method and says it's not a function. I used a workaround on init() to get it to work, but that method didn't work in save()
var vehicle = function () {
return {
init: function () {
var that = this;
jQuery('.vehicle-year-profile .options .delete').bind('click', function (e) {
e.preventDefault();
that.remove(jQuery(e.currentTarget).parents('.vehicle-year-profile'));
});
jQuery('.vehicle-year-profile .options .edit').bind('click', function (e) {
e.preventDefault();
that.edit(jQuery(e.currentTarget).parents('.vehicle-year-profile').attr('id'));
});
jQuery('#association-detail .save').bind('click', function (e) {
e.preventDefault();
that.save();
});
},
save: function () {
var data = new Array();
data['onSet'] = '';
var onSet = jQuery('#association-detail input:checked');
for (var i = 0; i < (onSet.length-1); i++) {
data['onSet'] = data['onSet']+','+onSet.attr('id');
}
var priceSet = jQuery('#association-detail input[type=text]');
for (var i = 0; i < (priceSet.length-1); i++) {
data['priceSet'] = data['priceSet']+','+priceSet.attr('id')+':'+priceSet.val();
}
jQuery.ajax({
type: 'post',
url: '/ajax/store/product/saveAssocDetail.php',
data: data,
success: function (r) {
if (r.length > 0) {
document.triggerNotification('check', 'Changes have been saved');
var that = this;
that.reset(); //ERROR IS TRIGGERED HERE
} else {
document.triggerNotification('x', 'Unable to save changes');
}
},
error: function () {
document.triggerNotification('x', 'Unable to process your request, ajax file not found');
return false;
}
});
},
reset: function () {
jQuery('#association-detail h3').html('');
jQuery('#assocationVehicleId').val('');
jQuery('#association-detail input:checked').attr('checked', false);
jQuery('#association-detail input[type=text]').val('0.00');
jQuery('#association-detail').hide();
}
}
}();
jQuery(function() {
vehicle.init();
});

Perhaps it's because you've made your reference to this inside your ajax call. Try putting this line:
var that = this;
before you make your ajax call, and then refer explicitly to that in your ajax call. So, something like:
var that = this;
jQuery.ajax({
type: 'post',
url: '/ajax/store/product/saveAssocDetail.php',
data: data,
success: function (r) {
if (r.length > 0) {
document.triggerNotification('check', 'Changes have been saved');
/**
* now you can refer to "that", which is in the proper scope
*/
that.reset(); //ERROR IS TRIGGERED HERE
} else {
document.triggerNotification('x', 'Unable to save changes');
}
},
error: function () {
document.triggerNotification('x', 'Unable to process your request, ajax file not found');
return false;
}
});

you should look at this: http://api.jquery.com/jQuery.proxy/ and also - check Function.bind prototype (ES5 spec) - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind or alt ways like http://webreflection.blogspot.com/2010/02/functionprototypebind.html
using that = this is fair but probably does not read as clearly.
jQuery ajax also supports context: this to rebind the callbacks for you automatically.

Related

how to disable more than one times when a link was click by user in Angularjs

I have using ViewItems() function in An-click='VewItems(id)' to call a method in Controller in Angularjs but it seem not good yet because when user click more time my images which load from Model it will get more image or element which I append to a div much as the amount of clicking.
Here is my Function
$scope.ViewItems = function ($id) {
$('.modal-title').html('');
$('#bookimg').html('');
// Fetch an item from book list
if($id) {
id = $id;
$http({
method: 'GET',
url: url+id,
}).then(function successCallback(response) {
var http_code = response.data.s_respond;
$('<div id="loading"></div>').appendTo('body');
if (http_code === 200) {
SetErrors(http_code, 'OK');
var book_items = JSON.parse(response.data.data);
$('<h3>'+book_items.title+'</h3>').appendTo('.modal-title');
$('<img src=" '+book_items.image+' " width="100%" />').appendTo('#bookimg');
$('#myModal').modal({backdrop: 'static', keyboard: false});
} else {
SetErrors(http_code, 'warning');
}
}, function errorCallback(response) {
SetErrors(http_code, response.textStatus);
});
}
};
HTML
Maintain a variable isClicked and handle the callback accordingly.
var isClicked = false;
$scope.ViewItems = function ($id) {
if (isClicked) {
return;
}
isClicked = !isClicked;
...
}
Just create an array to solve this
var loadedIds = [];
$scope.ViewItems = function ($id) {
var index = loadedIds.indexOf($id);
if(index == -1){
loadedIds.push($id);
-------
}
};

Uncaught Error: cannot call methods on progressbar prior to initialization; attempted to call method 'value'

I have an problem with my javascript code
Which gets an value from an ajax script and should update the progress bar.
<script>
function GetProgress(){
$.ajax({url: "percentage.php", success: function(result) {
console.log(result);
var pers = result;
$( "#progressbar" ).progressbar("value",pers.value);
if (pers.value > 0 )
isDone = true;
else
setTimeout(GetProgress(), 2000);
});
};
GetProgress();
</script>
It doesnt work with update it gets the value right but im getting this error:
Uncaught Error: cannot call methods on progressbar prior to initialization; attempted to call method 'value'
Please help :)
Before calling methods of a plugin, you need to initialize it
function GetProgress() {
$.ajax({
url: "percentage.php",
success: function (result) {
console.log(result);
var pers = result;
$("#progressbar").progressbar("value", pers.value);
if (pers.value > 0) {
isDone = true;
} else {
setTimeout(GetProgress, 2000);
}
}
});
};
jQuery(function () {
//initialize the plugin
$("#progressbar").progressbar();
GetProgress();
})
<script>
function GetProgress() {
$.ajax({
url: "percentage.php",
success: function (result) {
console.log(result);
var pers = parseInt(result);
$("#progressbar").progressbar("value", pers);
if (pers.value > 0) {
isDone = true;
} else {
setTimeout(GetProgress, 2000);
}
}
});
};
jQuery(function () {
//initialize the plugin
$("#progressbar").progressbar();
setTimeout(GetProgress, 2000);
})
</script>
Got the solution at last needed to make the value an integer.
Thanks for the solution!

How to combine two jQuery functions into one?

I've following two functions in jQuery:
$(document).on('change','.states',function(){
//on change of select
});
$(document).on('click','.date_control',function(){
//on click of input .date_control
});
How to combine the above two functions into one function so that I can use it with my AJAX function which is as below:
$(function() {
$(".add_new_rebate").on("click", function(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
});
});
If you have any other way than combining the above two function into one then also it will be fine. My requirement is to incorporate the code of these two functions into the above AJAX function as I'm generating the two HTML controls dynamically and I want to apply the jQuery classes to them. Thanks in advance.
JS:
function do_action(){
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
$(document).on('change','.states',function(){
//on change of select
do_action();
return false;
});
$(document).on('click','.date_control',function(){
//on click of input .date_control
do_action();
return false;
});
I'm assuming the reason why you asked the question is to avoid using the same code inside both events, this way, it's much cleaner. No repeating.
I am not that sure if I understood the point correctly, but I you can define a function withName () {}, so you can reference that function from withing the event handlers.
Here doStuff is called either on »change« or on »click«
function doStuff (e) {
//the stuff to do
}
$(document).on('change','.states', doStuff);
$(document).on('click','.date_control',doStuff);
I hope that is what you are asking for…
Please see this link:
How to combine two jQuery functions?
And the answer can answer your question:
you simply use the same selector for both your action and your confirm
function handler(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
$(document).on('change','.states', handler);
$(document).on('click','.date_control', handler);
If I understood your requirement correctly, then the following should work:
$( '.states, .date_control' ).on( 'click change', function ( event ) {
if( ( event.type == 'change' && event.target.className == 'states' )
|| ( event.type == 'click' && event.target.className == 'date_control' ) ) {
//process event here
};
} );

Create function for CamanJS Plugin

is there any chance to create a function that i can call?
if i'm putting the following lines in the document ready function it works:
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
this.brightness(brightness);
this.render(function () {
check = this.toBase64();
});
But if i'm doing this i can't call. So I tried this:
function icancall()
{
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
this.brightness(brightness);
this.render(function () {
check = this.toBase64();
});
}
So i thought i can call this with icancall(); But nothing happened. What am I doing wrong?
What i want do: executing the Caman function on a button click.
I hope you can help me !
function resz(){
Caman("25-02-2014_16-37-13.jpg", "#example-canvas", function () {
try {
this.render(function () {
var image = this.toBase64();
xyz(image); // call that function where you pass filters
});
} catch (e) { alert(e) }
});
}
[Apply CamanJS filters by this function]
function xyz(image){
var filters_k = $('#filters');
filters_k.click(function (e) {
e.preventDefault();
var f = $(this);
if (f.is('.active')) {
// Apply filters only once
return false;
}
filters_k.removeClass('active');
f.addClass('active');
var effect = $.trim(f[0].id);
Caman(canvasID, img, function () {
if (effect in this) {
this.revert(false);
this[effect]();
this.render();
}
});
});
}

How can I stop this setTimeout function from running?

I use the function below to check on the status of a JSON file. It runs every 8 seconds (using setTimeout) to check if the file has changed. Once the JSON's status becomes 'success' I no longer want to keep calling the function. Can someone please show me how to do this? I suspect it involves the use of clearTimeout, but I'm unsure how to implement this.
Cheers!
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
}
},
}).always(function () {
setTimeout(checkBookStatus, 8000);
});
};
checkBookStatus();
});
t = setTimeout(checkBookStatus, 8000); when you decide to stop the timeout use this clearTimeout(t);.
use clearTimeout
e.g. you defined :
id = setTimeout(checkBookStatus, 8000);
then you can remove this function by :
clearTimeout(id)
Before your call of checkBookStatus() at the end, put another call: var interval = setInterval(checkBookStatus, 8000);. Then on success you can clearInterval(interval).
Do not use setTimeout for iteration.
A lot of answers are suggesting just to use clearTimeout() however, you are checking the status after the timeout has expired, there is no timeout to clear. You need to not call setTimeout() in your always() function rather than to clear anything. So you could re-inspect the status inside your always() function I suppose, but your data object isn't in scope there. It would be preferable to just use setInterval() outside of your checkBookStatus() function.
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
clearInterval(interval);
}
}
});
};
var interval = setInterval(checkBookStatus, 8000);
checkBookStatus();
});
Call clearTimeout with the value previously returned by setTimeout. This would give you something like:
$(function() {
var timeoutID;
var checkBookStatus = function () {
[…]
else if (data.status == "#{Job.success}") {
clearTimeout(timeoutID);
[…]
}).always(function () {
timeoutID = setTimeout(checkBookStatus, 8000);
[…]
When you use setTimeout, use like this:
var myTime = setTimeout(checkBookStatus, 8000);
to clear it just:
clearTimeout(myTime);
the following should work...
the setTimeout function return an instance of the setTimeout function. Keep this value in a variable and pass it to the function clearTimeout when you want to prevent the event from firing again.
i.e.
var t = setTimeout(1000, someFunction);
...
//after you no longer need the timeout to fire, call
clearTimeout(t);

Categories

Resources