I have stupidly decided to support IE8 in my latest project, something which will no doubt go down in history as the dumbest idea of my life.
So the most fundamental problem I'm running into is that my main class variable is undefined. What I mean is I have a prototype set up in a file general.js that looks a bit like this:
var generalClass;
// jQuery Object
var $ = jQuery;
$(document).ready(function() {
// A general class for a general file.
generalClass = function() {
}
generalClass.prototype = {
}
new generalClass();
});
So the generalClass variable is filled up with my prototype/etc. I then include this in the head of my document and later on I call upon a function in that generalClass for something else, a bit like this:
<script type="text/javascript" src="general.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: ...,
data: {
},
success : function(data) {
// CALL MY FUNCTION:
generalClass.prototype.myFunction();
}
}
});
</script>
In every browser, from IE9 to Chrome this works. In IE8 this does not work, and generalClass is undefined. Why is it doing this to me?
I am not sure where you learned that pattern, but it should be more like this:
var generalClass;
// jQuery Object
//var $ = jQuery; <-- makes no sense $ should be jQuery already
$(document).ready(function() {
function GeneralClass() {}
GeneralClass.prototype = {
myFunction: function () {
alert("x");
}
};
generalClass = new GeneralClass();
});
and when you call it
generalClass.myFunction();
Related
I need to access a js variable declared in one block of a html page into another block of the same html page just so I can stop a ajax call that is being made, but I don't know how can I access a variable that was declared into another block. I can't merge the two blocks, everything else is on the table.
<script>
$(function() {
var term = new Terminal('#input-line .cmdline', '#container output');
term.init();
});
</script>
<script>
term.ajaxHandler.abort();//but how can I access the variable term from the block above,this will be inside a button later
</script>
Thanks in advance
The way your code example is described, it's not possible to reuse that variable. Because it is not bound to the window object, it's bound to the function that is self-executed. It's an example of a "safe" way of libraries not intervening with your own code.
You can however, since I guess by the syntax it's jQuery, hook into the jQuery ajax handling. Based on your requirements, to stop an ajax call, you need to listen to all ajax requests.
You could take a look at the jQuery ajax hooks, https://api.jquery.com/category/ajax/.
You could end up with something like:
$(document).ajaxSend(function(event, xhr, settings){
if (settings.url === "/your/url/to/abort") {
xhr.abort();
}
});
just declare var term above the function declaration
var term
function test1(){
term = 'hello there'
test2()
}
function test2(){
console.log(term)
}
test1()
ok, I managed to solve, basically I created a function only to abort the ajax request like this:
this.abortAjax = () => {
requestHandler.abort();
}
and then accessing it within terminal.js itself using the term object that was instantiated beforehand. After working around the code I was able to keep everything inside the terminal script and not splitted in the two parts, getting something like this:
function ShowLoadingScreen () {
var customElement = $("<div>", {
"class" : "btn btn-danger btn-lg",
"text" : "Abort",
"onclick": "term.abortAjax()"
});
$.LoadingOverlay("show", {
//image : "/static/loading.gif",
background : "rgba(204, 187, 0, 0.8)",
imageAnimation : "rotate_right",
//imageAutoResize : true,
text : "Loading...",
custom : customElement
});
}
function request (command) {
...
requestHandler = $.ajax({
url: _url,
beforeSend: function () { ShowLoadingScreen(); }, // <Show OverLay
type: 'GET',
dataType: 'json',
success: function (response) {
...
},
complete: function () { HideLoadingScreen(); } //<Hide Overlay
}).fail(function (jqXHR, textStatus, error) {
...
});
ShowLoadingScreen();
}
Thanks, everyone.
A very interesting problem I am facing these days is regarding one of my JavaScript function. My JavaScript function with some specific name is not working but if I change its name to anything else then it is working. Have a look -
// function to retain the jquery ui css for toolbar
function retain_css() {
alert('hi');
$( "#new_sort_options" ).buttonset();
}
// new sort
$(document).on("click", ".new_sort_button", function() {
var order = $(this).val();
var make_id = $('#new_make_id').val();
$.ajax({
beforeSend : start_loader(),
type : 'POST',
url : '/ajax/new-sort.php',
data : 'order='+order+'&make_id='+make_id,
dataType : 'json',
success : function(data) {
$("#new_results_toolbar").html(data.toolbar);
$("#new_results").html(data.models);
retain_css();
end_loader();
}
});
});
But retain_css() is not working at all. Even alert() is not firing. But if i change its name to anything such as my_fun() then the code works. I don't understand why it is happening so? Any idea? Don't worry about end_loader() function as it has nothing to deal with my problem. I also changed the order of code when retain_css() was being used but didn't work.
Try not to create global functions because it may collide with other frameworks or libraries.
//define private namespace
window.user3779493Functions = {};
//define method
user3779493Functions.retain_css = function() { ... }
//call method
user3779493Functions.retain_css();
Some functions are already programmed like 'alert('hi');', that is a function called alert:
function alert() {
/* do something */
}
That function also doesn't work.
I have the following scripts:
<script ... jquery-1.9.1.js"></script>
<script ... dataTables.js"></script>
<script ... columnFilter.js"></script>
The following code exists in columnFilter.js:
(function ($) {
$.fn.columnFilter = function (options) {
//some code...
function _fnCreateCheckbox(oTable, aData) {
//some code...
}
};
})(jQuery);
What I would like to do is override function _fnCreateCheckbox(oTable, aData) with my own code. Im fairly new to javascript, so would appreciate an example.
I have tried simply grabbing the code above and adding it to it's own <script> tags, but that didn't work. It completely stopped the columnFilter.js from working (which is as expected I guess). Not really sure what else to try.
function _fnCreateCheckbox(oTable, aData) {
Only exists in the scope in which it was created as (function ($) { creates a function scope. You must edit it there. You can't override it outside the function.
EDIT: On a related note
If you are crafty with JS and you are trying to get that function to do something else only sometimes, you could pass some extra variables into your columnFilter plugin/function call and handle them in that function to do something else. I have no idea what column filter is, but let's pretend to call it on an element like so:
el.columnFilter({optionA: true, optionB: false});
If you wanted to do something else based on some data you have you could do,
el.columnFilter({optionA: true, optionB: false, extraOption: true});
Then in your script, depending on what your entire script does:
$.fn.columnFilter = function (options) {
//some code...
if(options.extraOption){
function _fnCreateCheckbox(oTable, aData) {
//some default code...
}
} else {
function _fnCreateCheckbox(oTable, aData) {
//my other code...
}
}
};
This is a crude example, but just to display your options.
I suppose you import the columnFilter.js file from some external source.
One option could be to copy the columnFilter.js file to your project's directory, modify it as you please and then import it from your project's directory.
You can override a function by reassigning its prototype. It is generally advised against though.
var d = new Date();
alert(d.getFullYear()); // 2013
Date.prototype.getFullYear = function() { return "Full Year"; }
alert(d.getFullYear()); // "Full Year"
http://jsfiddle.net/js5YS/
I have an external javascript file that I want to use to collect the contents of a number of text files. JQuery .get() seems the most obvious choice. I can make this work if the JQuery is in the page, but not when the JQuery is in the external file. I'm missing something hugely simple...and I am currently mixing normal javascript with JQuery in the same file which I fear is poor form.
All files I am trying to access are within the same file structure. Currently I have the following in my external .js:
function addPanels() {
// eventually loop over list of local HTML files
// and do some stuff with the results...
fileContents = readHTMLFile();
}
jQuery(function($){
readHTMLFile = $.get('../html/test.html', function(data) {
alert('Loaded something');
return(data);
});
});
My HTML page contains the following:
<script type="text/javascript">
$(document).ready(function(){
addPanels();
});
</script>
Pretty sure this is a RTFM moment so direction towards the right manual/tutorial would be great!
Dan
The jQuery.get is a asynchronous function, with a callback that executes when the server returns the requested document. Therefore, you cannot return any data from the method.
function addPanels() {
// will not work
fileContents = readHTMLFile();
}
...
readHTMLFile = $.get('../html/test.html', function(data) {
// will not work
return(data);
});
This however, will work:
var addPanelCallback = function(html) {
// append html (or something like that)
alert(html);
};
var addPanel = function(url) {
$.get(url, addPanelCallback);
};
addPanel('../html/test1.html');
addPanel('../html/test2.html');
Example: http://jsfiddle.net/FgyHp/
In your script "readHTMLFile" is not known by function "addPanels", you should put them in same level.
This script should works
<script type="text/javascript">
(function($){
var readHTMLFile = function(url){
var toReturn;
$.ajax({
url: url,
async: false
}).done(function(data){
toReturn = data;
});
return toReturn;
};
$.addPanels = function(url){
fileContents = readHTMLFile(url);
};
})(jQuery);
</script>
And in your page you can call it like that:
<script type="text/javascript">
$(document).ready(function(){
$.addPanels('../test/test.html');
});
</script>
I am using jQuery and YUI-3.6.0 in my application. I am using YUI history module. I trie to create a wrapper on YUI history as below. (This is saved in "history-wrapper.js")
var MyHistory;
(function() {
YUI().use('history', function (Y) {
var history = null;
MyHistory = function() {
history = new Y.History();
};
MyHistory.prototype.save= function() {
history.add({
data : "some data"
});
};
MyHistory.prototype.load= function() {
var data = (history.get("data");
//process data
};
});
})();
I am using this wrapper with following lines of code
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="yui/yui/yui-min.js"></script>
<script type="text/javascript" src="js/history-wrapper.js"></script>
<script type="text/javascript">
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var history = new MyHistory();
history.save();
});
</script>
I am using same code in two different application.
In one application, everything works fine as Wrapper is loaded first.
In other application it throws "MyHistory is not defined" as "jQ(document).ready" function is called before wrapper is loaded.
I have no idea what causes this behavior. Can anyone help me?
The callback function "function(Y){... where you define MyHistory...}" in the YUI.use() is only executed when the dependendies (history) are loaded.
Then, you have no assurance MyHistory is defined when you try to use your wrapper.
The solution may be you put your JQuery code in the the YUI.use() too. You can make the YUI loader load jquery and the history module, you the no longer need to wrap the Histroy plugin.
I'm not sure it is exactly like this (cannot check it now).
<script type="text/javascript" src="yui/yui/yui-min.js"></script>
YUI({
modules: {
'jquery': {
path: 'js/jquery.js'
}
}
}).use('history', 'jquery' , function (Y) {
var jQ = Y.jQuery.noConflict(); //or juste jQuery.noConflict();
jQ(document).ready(function() { //it is likely the document will already be ready
var history = new Y.History();
history.save();
});
});