JS - accessing global variable issue - javascript

Best described by example:
I have the following piece of code:
/* YIELDS ERROR
$('body').on('DOMNodeInserted', '.zeon-merchandise-measure', function () {
dropdownCssClass : 'zeon-select2-dropdown',
data: merchandise_measures
});
*/
// OK
$(".zeon-merchandise-measure").select2({
dropdownCssClass : 'zeon-select2-dropdown',
data: merchandise_measures
});
I can't undesrand what is wrong with scope. The second function works ok, while DOMNodeInserted-part cannot recognize merchandise_measures
Here's how `merchandise_measures is defined (html page being loaded)
<script type="text/javascript">
// A global variables
merchandise_measures = {{ merchandise_measures_json|safe }};
</script>
What am I doing wrong?

First example has invalid syntax. You are passing a function and using it as an object. I don't know your whole code and what are you trying to achieve but this is more valid:
$('body').on('DOMNodeInserted', '.zeon-merchandise-measure', function () {
var myObject = {
dropdownCssClass : 'zeon-select2-dropdown',
data: merchandise_measures
}
});

Related

Accessing a JS variable from a different <script> block

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.

Javascript CallBack with same function name in multiple pages

My objective is to perform Auto-Complete feature of the same context in multiple pages/Views, for same input having the same class name (i.e. Client Name to be auto complete for many pages like Create and Edit View and others).
Since I need to call the jquery's autocomplete() in each page, I had written in
Views\Shared_Layout.cshtml
page of my project so the auto complete feature will available where required. The code I had written in _Layout.cshtml is as follows:
<script>
$(document).ready(function () {
//common
$('.form-control.salescode').autocomplete({
minLength: 4,
source: '#Url.Action("GetAccountManager", "AccountManager")',
select: callBackSalesCodeLookUp
});
});
</script>
Then any View (Create or Edit) which requires, the auto-complete feature have this code called:
<script>
function callBackSalesCodeLookUp(event, ui)
{
event.preventDefault();
var selectedArr = ui.item.value.split("|");
var accountManagerID = selectedArr[0];
var accountManagerName = selectedArr[1];
$('.form-control.salescode').val(accountManagerID);
}
</script>
However, when I ran the project, I am getting an error for pages which have not having the following code, which is as expected:
function callBackSalesCodeLookUp(event, ui)
{
event.preventDefault();
var selectedArr = ui.item.value.split("|");
var accountManagerID = selectedArr[0];
var accountManagerName = selectedArr[1];
$('.form-control.salescode').val(accountManagerID);
}
The error I am getting, is in Chrome as :
jquery-3.1.1.js:3855 Uncaught ReferenceError: callBackSalesCodeLookUp
is not defined
at HTMLDocument. (Login?ReturnUrl=%2FAccountOpeningRegister%2FCreate:393)
at mightThrow (jquery-3.1.1.js:3570)
at process (jquery-3.1.1.js:3638)
I want to less the code, and which is the reason I made up something like this. I will be glad to know if there is any better way of coding this.
Thank You
Check if the function exists in the window before calling it.
<script>
if (typeof callBackSalesCodeLookUp == 'function') {
$(document).ready(function () {
//common
$('.form-control.salescode').autocomplete({
minLength: 4,
source: '#Url.Action("GetAccountManager", "AccountManager")',
select: callBackSalesCodeLookUp
});
});
}
</script>

Obout.Interface.OboutTextBox' is null or not an object error

When I use my below JS FIDDLE, I get error as
Obout.Interface.OboutTextBox' is null or not an object in IE.
I don't know what is the issue here
I get error at line no 308 which is
Obout.Interface.OboutTextBox.prototype.applyCrossBrowserFixes = function (){}
Here is my Fiddle
Please suggest what is wrong
Ensure those function is not wrapped around by document ready. Place it only inside <script></script> :
Not like this :
<script>
// or $(document).ready(function(){
$(function(){
function navigateThroughCells(sender, key, forced) { .... }
});
</script>
But like this :
<script>
function navigateThroughCells(sender, key, forced) { .... }
</script>

Why a JavaScript function with some specific name is not working while others are?

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.

Class is undefined in IE8

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();

Categories