React component intermitently working in chrome, debug for stability - ruby-on-rails

This code has been working fine, but now it's working intermittently in chrome. Does anyone know what might be causing this. If so what can I do to increase stability in chrome
This function opens a pop up modal with the project form react component.
editProject: function(i) {
$('#agency_projects').trigger(
"projects:open",
[this.state.projects[i].showUrl, true]
);
},
getInitialState: function() {
return {
...
/* TODO Refactor to prevent props in initialState */
projectId: this.props.projectId,
projectUrl: this.props.projectUrl,
}
},
The initial state has the project id, and url stored which is used to submit an ajax request to pull in the project.
componentDidMount: function() {
if(this.props.projectUrl) {
$.getJSON(this.state.projectUrl)
.done(function(data) {
if(!this.isMounted()) {
return;
}
this.setState({
title: data.title,
externalUrl: data.externalUrl,
client: data.client,
description: data.description,
content: data.content,
});
}.bind(this))
.fail(function(jqXHR, status, err) {
console.error(jqXHR, status, err);
});
}
},
The form renders as suspected, but the data is only pulled every now and again.

Related

jQuery UI Tooltip delayed loading

When hovering over a link, I'd like to wait at least a second before showing a tooltip with dynamically loaded tooltip.
What I've created is the follow jQuery Code:
$(document).ready(function () {
$("div#galleries ul li:not(.active) a").tooltip({
items: "a",
show: { delay: 1000 },
content: 'Loading preview...',
open: function (event, ui) {
previewGallery(event, ui, $(this));
}
});
});
function previewGallery(event, ui, aLinkElement) {
event.preventDefault();
ui.tooltip.load("http://www.someurl.com/Preview.aspx #preview");
}
Which seemed to work pretty fine, you can see it here:
http://fotos.amon.cc/ (simply hover over the list of galleries)
But I didn't realize at the beginning, that the loading of preview text happens immediately when hovering over the link. So if you quickly hover over all the links, you'll set up several requests:
From the users point of view (without knowing that requests are fired) it looks already the way I want, but how to only start loading the preview, when tooltip is actually showing up?
Thanks,
Dominik
What I did in the end was to use window.setTimeout and window.clearTimeout:
var galleryToolTipTimer = null;
var previewElement = null;
$(document).ready(function () {
$("div#photos div a img").tooltip();
$("div#galleries ul li:not(.active) a")
.tooltip({ items: "a", content: 'Loading preview...', disabled: true, open: function (event, ui) { previewElement.appendTo(ui.tooltip.empty()); } })
.mouseover(function (e) {
if (galleryToolTipTimer != null) { window.clearTimeout(galleryToolTipTimer); }
var aLinkObject = $(this);
galleryToolTipTimer = window.setTimeout(function () { previewGallery(aLinkObject); }, 500);
}).mouseleave(function (e) {
window.clearTimeout(galleryToolTipTimer);
$(this).tooltip("option", { disabled: true });
});
});
function previewGallery(aLinkElement) {
previewElement = $("<div/>").load(aLinkElement.closest("div").data("galleryPreview") + "/" + aLinkElement.data("path") + " #preview", function () {
aLinkElement.tooltip("open");
});
}
Works at least the way I want.
To see it in action, simply navigate to http://fotos.amon.cc/ and hover over one of the gallery links on the left for a preview:

Firefox addon progress listener

I am using this page to implement an address bar change listener.
https://developer.mozilla.org/en-US/docs/Code_snippets/Progress_Listeners#Example.3a_Notification_when_the_value_in_Address_Bar_changes
This code does what it is supposed to do. When I navigate to a new page, it alerts the URL. However, if the URL I have is 302 or similar it causes an issue. It will alert the redirected URL and not the original URL. I need the URL before the request is sent to the server and the redirect happens. Is this possible?
I think you can check this via the onStateChange event.
var myExtension = {
oldURL: null,
init: function() {
gBrowser.addProgressListener(this);
},
uninit: function() {
gBrowser.removeProgressListener(this);
},
processNewURL: function() {},
// nsIWebProgressListener
QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener",
"nsISupportsWeakReference"]),
onLocationChange: function(aProgress, aRequest, aURI) {
this.processNewURL(aURI);
},
onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
if (!aRequest) return;
if (aStateFlags & nsIWebProgressListener.STATE_START) {
alert(aRequest.name);
},
onProgressChange: function() {},
onStatusChange: function() {},
onSecurityChange: function() {}
};
window.addEventListener("load", function() { myExtension.init() }, false);
window.addEventListener("unload", function() { myExtension.uninit() }, false);
See more here: https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIRequest
aRequest is a nsIRequest, whose property name is the URL of the request.

How to validate select with JQuery.Validate while using JQueryMobile

I'm just exploring the Validate plug-in for JQuery. During implementing in my webapp made with JQueryMobile I stumbled over the fact that validating such an element is not so simple like usual input-elements.
So the Question is: How to enable validation for select?
The trick consists out of two parts:
Validate is by default ignoring :hidden. But that's what JQM does with an <select>: hide it and placing a div-span-wrapper on top. Solution is to redefine the ignore-selector:
{ignore: ":hidden:not(select)"}
To inform the user about the invalid field you have to show the error right on the wrapper:
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput")
And now in an working example:
$.validator.setDefaults({
debug: true,
ignore: ":hidden:not(select)",
submitHandler: function() { alert("submitted!"); },
showErrors: function(map, list) {
$(this.currentElements).each(function() {
if(this.nodeName == "SELECT") {
$(this).closest('.ui-select').removeAttr("title").removeClass("invalidInput");
return true;
}
$(this).removeAttr("title").removeClass("invalidInput");
});
$.each(list, function(index, error) {
if(error.element.nodeName == "SELECT") {
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput");
return true;
}
$(error.element).attr("title", error.message).addClass("invalidInput");
});
}
});
$('div[data-role="page"]').bind('pageinit', function(event) {
var rules = {};
$('input:not(:button)').each(function() {
rules[this.name] = {required:true};
});
$('#fzgherst').each(function() {
// revalidates the select when changed, other elements gets revalidatet onblur
$(this).on('change', function() {$(this).valid();});
rules[this.name] = {required:true};
});
$("form").validate({
rules: rules
});
});
That's all folks!

Post data to controller with JQuery via login screen

I have a section in my ASP.NET MVC3 website where a user can click a button to add an entry to their 'Saved Items' section in their account. This is done via a JQuery Ajax request, which works well if they're logged in. If they're not logged in, I'd like them to be redirected to a login page, and then automatically have the entry added to their Saved Items section.
I have all the parts working seperately - i.e. when the button is clicked, if not logged in, the login box displays. The login popup also works successfully. The problem is trying to seamlessly do all things at once. Here is the code I have so far:
Click event for Save button - checks to see if user logged in along the way:
var loggedIn = false;
$(document).ready(function () {
$('a#saveSearch').live('click', function (event) {
$.get('#Url.Action("IsLoggedIn", "Account", null)', function (response) {
if (response == "True")
loggedIn = true;
else
loggedIn = false;
});
if (loggedIn){
SaveSearch();
}
else{
$('#dialog').dialog('open');
SaveSearch(); //don't think this is correct because it hits this line before login is complete
}
});
Function to save to database:
function SaveSearch(){
var url = '#Url.Action("SaveSearch", "User")';
$.ajax({
url: url,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
json: "#Html.Raw(Session["MyFormString"].ToString())"
}),
success: function (data) {
$('a#saveSearch').attr('disabled', "disabled");
$('div#savedResponse').html('<p>Search saved to user account</p>');
},
error: function () {
}
});
}
});
JQuery UI dialog popup:
$(function () {
$('#dialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Login',
modal: true,
open: function(event, ui) {
$(this).load("#Url.Action("Logon", "Account", null)");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
I think there is something fundamental that is wrong with my code, because this way, the login popup appears for just a second and then disappears straight away. It looks like I need to get it to stop advancing through the code until the login has been completed.
Any advice or help to get this going would be appreciated.
I would imagine your issue might be related to:
$.get('#Url.Action("IsLoggedIn", "Account", null)', function (response) {
if (response == "True")
loggedIn = true;
else
loggedIn = false;
});
if (loggedIn){
SaveSearch();
}
else{
$('#dialog').dialog('open');
SaveSearch(); //don't think this is correct because it hits this line before login is complete
}
The $.get call is async, which means the latter code:
if (loggedIn){
Is being executed before the server has responded. You need to put that code within your response callback:
$.get('#Url.Action("IsLoggedIn", "Account", null)', function (response) {
if (response == "True")
loggedIn = true;
else
loggedIn = false;
if (loggedIn){
SaveSearch();
}
else{
$('#dialog').dialog('open');
SaveSearch(); //don't think this is correct because it hits this line before login is complete
}
});
Try and add a close callback function to your modal, then the code will only be done as soon as the modal is closed and all the login have been done sucessfully. See comments in your code
$(document).ready(function () {
$('a#saveSearch').live('click', function (event) {
$.get('#Url.Action("IsLoggedIn", "Account", null)', function (response) {
if (response == "True")
loggedIn = true;
else
loggedIn = false;
});
if (loggedIn){
SaveSearch();
}
else{
//in this dialog, add a close handler,then add the SaveSearch(); function in that handler
$('#dialog').dialog('open');
}
});

jQuery UI autocomplete (combobox): how to fill it with the result of an AJAX request?

Is it possible to work with combobox as with usual jquery-ui ajax autocomplete field?
What I need?
I want there will be some default options and when user try to put any letters it must connect to the server to find requested information (as usual remote json autocomplete).
Is it possible at all?
Here's a heavily modified version of the jQueryUI example (gist):
$.widget("ui.combobox", {
_create: function() {
var _self = this
, options = $.extend({}, this.options, {
minLength: 0,
source: function(request, response) {
if (!request.term.length) {
response(_self.options.initialValues);
} else {
if (typeof _self.options.source === "function") {
_self.options.source(request, response);
} else if (typeof _self.options.source === "string") {
$.ajax({
url: _self.options.source,
data: request,
dataType: "json",
success: function(data, status) {
response(data);
},
error: function() {
response([]);
}
});
}
}
}
});
this.element.autocomplete(options);
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(this.element)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function() {
if (_self.element.autocomplete("widget").is(":visible")) {
_self.element.autocomplete("close");
return;
}
_self.element.autocomplete("search", "");
_self.element.focus();
});
}
});
Usage:
$("input_element_selector").combobox({
initialValues: ['array', 'of', 'values'],
source: /* <-- function or string performing remote search */,
/* any other valid autocomplete options */
});
Example: http://jsfiddle.net/Jpqa8/
The widget uses the supplied initialValues array as the source when the length of the search is "0" (this happens when the user clicks the dropdown button).
Supply a source parameter (function or string) that performs the remote search. You can also use any other options you would usually use with the autocomplete widget.

Resources