jQuery Event Bubbling on wrong object - javascript

I'm still a little new to jQuery events.
I'm trying to write jQuery a wrapper/framework of the Asp.NET UpdatePanel that automatically tracks UpdatePanel async updates.
I want to be able to do something like
$("#myUpdatePanel").on("update", myFunc);
and have it run some handler with this as the updated UpdatePanel. I actually have this bit working.
I also want to be able run a function exactly once any time one or many UpdatePanels update.
$.updatePanel.on("update", myRunOnceFunc);
This is where I'm having issues.
I've defined my wrapper:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
var prm;
var UpdatePanel = function () { };
UpdatePanel.prototype = { };
// initialize on $(document).ready()
$(function () {
prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm) {
prm.add_pageLoaded(function (s, e) {
$.each(e.get_panelsUpdated(), function () {
// call panel-specific update event handlers
$(this).trigger($.Event("update"));
});
// triggered once no matter how many panels were updated
$(UpdatePanel).trigger($.Event("update"));
});
}
});
return $(UpdatePanel);
})();
Then in my code that uses $.updatePanel:
$(function() { $.updatePanel.on("update", myRunOnceFunc); });
What I'm finding is that myRunOnceFunc is being run during both $(this).trigger($.Event("update")); and $(UpdatePanel).trigger($.Event("update"));.
Any ideas why and how to fix it?

I figured out what was wrong.
Rather than return $(UpdatePanel);, I needed to call return $(new UpdatePanel());. Then I needed to replace $(UpdatePanel).trigger(...) with $.updatePanel.trigger(...). Code below:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
var prm;
var UpdatePanel = function () { }
UpdatePanel.prototype = { };
$(function () {
prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm) {
prm.add_pageLoaded(function (s, e) {
$.each(e.get_panelsUpdated(), function () {
$(this).trigger($.Event("update"));
});
// triggered once no matter how many panels were updated
$.updatePanel.trigger($.Event("update"));
});
}
});
return $(new UpdatePanel());
})();

Related

Click not triggered on Javascript function that submits to Facebook Pixel

The following code tracks the number of clicks on the element and then submits the result to Facebook Pixel. However, the event is not triggered for some reason.
Thought it's a variable scope problem, changed countClicks to global but it didn't change anything.
$(document).ready(function () {
if(window.location.href.indexOf("products") > -1) {
var countClicks = 0;
$(".product-single__thumbnail-image").click(function () {
countClicks++;
});
function firePixelSlideshowView() {
fbq('trackCustom', "ProductSlideshowImageView", {
imageView: countClicks,
});
}
window.onbeforeunload = function () {
firePixelSlideshowView();
return null;
}
}
});
I solved the problem by using jQuery unload() function instead of vanilla Javascript and it worked.

A JavaScript function is repeated many times

I have two function print and callPrint bellow. I click call function print the first time is right.
But when click call function print the second or third then function callPrint will be call 2 times or 3 times.
I have debug on attack file.
function print(url) {
console.log('print');
var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint');
if ($iframe.attr('src') != url) {
$.when(
$iframe.attr('src', 'about:blank'),
$iframe.load(function () {
console.log($iframe.prop('contentWindow').document.readyState);
})
).done(function () {
$iframe.attr('src', url);
$iframe.load(function () {
console.log('new');
_this.callPrint(iframeId);
});
});
} else {
console.log('old');
_this.callPrint(iframeId);
}
}
// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
console.log('callPrint');
$('div.wait').hide();
var PDF = document.getElementById(iframeId);
PDF.focus();
PDF.contentWindow.print();
return false;
}
A JavaScript function is repeated many times
The problem is because you're attaching two new load() event handlers to the iframe every time print() is called. To fix this, add a single load() event handler and call your function from in there. This will be triggered whenever you update the src attribute on the element. Try this:
var $iframe = $('#iframeprint').load(function() {
// You'll need to make sure the function is in scope of the handler
// There's not enough information in the OP for me to show you how
callPrint('iframeprint');
});
function print(url) {
var _this = this;
if ($iframe.attr('src') != url) {
$iframe.attr('src', url);
} else {
_this.callPrint(iframeId);
}
}
Thanks "Rory McCrossan". I add setTimeout function when callPrint so dialog print will open. But I can't vote for you at the moment.
var $iframe = $('iframe#iframeprint').load(function () {
// You'll need to make sure the function is in scope of the handler
// There's not enough information in the OP for me to show you how
setTimeout(function () {
callPrint('iframeprint');
}, 100);
});
function print(url) {
if ($iframe.attr('src') != url) {
$iframe.attr('src', url);
} else {
console.log('old');
callPrint('iframeprint');
}
}
// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
$('div.wait').hide();
var PDF = document.getElementById(iframeId);
PDF.focus();
PDF.contentWindow.print();
}

Jquery Dailog not returning the user given value for Confirmation PopUp.

Hi I'm using JQUERY Dialog for a confirmation popup. I have a common javascript file, in which i had a function which used to call window.ShowModalDialog. Now from the same function i am calling the jquery dialog, but as it is an asynchronous call, the calling function returns the value(yes/no) without even accepting Values from dialog. How can i return the proper value(yes/no)
If I have correctly understood the problem ...
and if something is wrong, add the example of your code
Try using this pattern:
(function ($, undefined) {
$.fn.dialog = function (options) {
options = $.extend({}, $.fn.dialog.options, options);
return this.each(function () {
var dialog = $(this);
dialog.children(".ok").click(function (e) {
options.ok.call(this, e);
dialog.close();
});
dialog.children(".close").click(function (e) {
options.close.call(this, e);
dialog.close();
});
});
};
$.fn.open = function () {
this.get(0).showModal();
};
$.fn.close = function () {
this.get(0).close();
};
$.fn.dialog.options = {
ok : function () {},
close : function () {}
};
})(jQuery);
and using callback
var dialog = $(".myDialog").dialog({
ok : function () {
alert("ok!!");
}
});
Do everything you need in callback, but avoid callbackhell.
see example

How to remove/reset window.onfocus function?

This has been driving me nuts.
When i load a page i initiate a window.onfocus function:
initializeFocusDetecttor: function () {
window.onfocus = function () {
var options = {
useFade: false
}
$.OverWatch.worker.getView("/OverWatch/UpdateWatch", function () {
$.OverWatch.init();
}, options);
}
}
However I don't want this behavior on every page but I don't know how to remove/reset this.
I have tried
window.onfocus = null;
window.onfocus = function(){return;};
window.onfocus = "";
but it does not work
if you change it to use jQuery event handling, you can just remove it (e.g. with off).
initializeFocusDetecttor: function () {
$(window).on('focus.mine', function () {
var options = {
useFade: false
}
$.OverWatch.worker.getView("/OverWatch/UpdateWatch", function () {
$.OverWatch.init();
}, options);
});
});
// Some condition - turn it off
$(window).off('focus.mine');
This example adds the custom namespace .mine to the event name so that you can target it specifically without affecting other code using focus events.

Managing and Maintaining too many on click jquery handlers

I recently have been upgrading the Phonegap to the latest version and now it forces me to follow the Chrome's Content Security Policy which in a way is good. But now I am forced to remove the all the onclick handlers in the HTML code and add them in the jquery handler some$(document).ready(function(evt){
$('#addRecordBtn').on('click', function(){
alert("Adding Record");
AddValueToDB();
});
$('#refreshBtn').on('click', function(){
alert("Refresh Records");
ListDBValues();
});
});
But as per what my app is scaled upto I feel that there will be too many of these handlers. Is there an example which shows maintenance of such handlers and a proper way or proper place of defining such handlers.
Here's an idea. You could make an object that stores all of the functions that also knows how to give up the function
var handlers = {
getHandler: function (str) {
return this[str];
},
'#addRecordBtn': function () {
alert("Adding Record");
AddValueToDB();
},
'#refreshBtn': function () {
alert("Refresh Records");
ListDBValues();
}
};
Then apply all of your handlers using this form.
$('#addRecordBtn').on('click', handlers.getHandler('#addRecordBtn'));
$('#refreshBtn').on('click', handlers.getHandler('#refreshBtn'));
Optimization Time if you want to get really fancy and you assign a unique ID to every button as convention
var handlers = {
defer: function () {
return function (){
handlers[$(this).attr('id')](arguments);
};
},
registerHandlers: function () {
for (var key in this) {
if (this.hasOwnProperty(key) && typeof(key) === "string") {
$('#' + key).on('click', this.defer());
}
}
},
'addRecordBtn': function () {
alert("Adding Record");
AddValueToDB();
},
'refreshBtn': function () {
alert("Refresh Records");
ListDBValues();
}
};
call it with
$('#addRecordBtn').on('click', handlers.defer());
$('#refreshBtn').on('click', handlers.defer());
or register everything automatically
handlers.registerHandlers();
Here is a fiddle of my solution
Do you look for something like this?
$('[data-clickhandler]').on('click', function(e) {
var $btn = $(e.currentTarget);
var handler = $btn.data('clickhandler');
alert('Refresh ' + handler);
window[handler] && window[handler](e);
e.preventDefault();
});
Now your elements can specify their clickhandler like so:
<a data-clickhandler="AddValueToDB" href="">...</a>
Or so:
<span data-clickhandler="ListDBValues">...</span>

Categories