Change javascript variable with jquery - javascript

In my MVC project i import a .js file in my shared layout.
<script src="#Url.Content("~/Scripts/bootbox.js")" type="text/javascript"></script>
This file has this variable
var locales = {
en: {
OK: "OK",
CANCEL: "Nej",
CONFIRM: "Ja"
}}
In one of the views i would like to change the OK value for en with jQuery. How can i do this?

Assuming the file defines locales as a global variable,
locales.en.OK = 'en';
To be clear, though, this has nothing to do with jQuery, razor, or model-view-controller. It's simply how you set the property of an object in native Javascript, there's no further technology required to do this.
I have now downloaded bootbox.js myself to look at what's going on here. locales is not defined as a global variable, it's scoped to the anonymous wrapper function that contains all of the contents of bootbox.js.
This means that there is no way to change the contents of that variable dynamically from outside of that scope. If you want to permanently change that text, then you can change it in bootbox.js manually. If you want to change it dynamically, then you can replace
var locales = ...
with
window.locales = ...
in bootbox.js, and then use my original suggestion in your own code.

You may declare locales in some scope, define locales outside of scope that is global or just remove var from locales as mentioned below.
locales = {
en: {
OK: "OK",
CANCEL: "Nej",
CONFIRM: "Ja"
}}
You can call it by locales.en.OK

Related

How do I call upon my settings (array) listed in html using prototype in my javascript file?

I'm relatively new to javascript development and have tried to construct my own framework. I've been trying to convert my standard javascript functions to a framework. However I've been stuck at a relatively simple (I think), but nowhere explained issue.
In my HTML I call on the settings I want to use in my JavaScript (the user has to be able to edit them in html, not in js as it will be minified).
<script>
$(document).ready(function(){
var settings = {authenticFilter: 'on',
randomizeHeaders: {state: 'on', topHeader: 'h1', bottomHeader: 'h2'},
};
var papery = new Papery(settings);
});
</script>
But I can't seem to figure out how to use the settings I have given to my framework in the javascript file.
I know I can call upon this.settings = settings; in my javascript file, but in an if statement below, I want make use of specific settings in the given settings. However this option and several other ways I've tried to use the settings won't work. Can I even use the settings I give to the prototype from my html in an array?
var Papery = function (settings) {
Papery.authenticFilter = function() {
if (Papery.authenticFilter == 'on'){
$("img").addClass("authenticFilter");
$(".authenticFilter").css({"filter": "sepia(80%) grayscale(1) contrast(1) opacity(0.7)", "-webkit-filter": "sepia(80%) contrast(1) opacity(0.7)"});
}
}
}
You are using Papery.authenticFilter instead of settings.authenticFilter. Keep in mind that in usual libraries, a bunch of default settings are set in initialization in case they are not defined on the settings passed on the constructor.

interacting with javascript through the chrome console [duplicate]

This question already has answers here:
Console access to Javascript variables local to the $(document).ready function
(8 answers)
Closed 6 years ago.
I'm using a shopping cart api to build an ecommerce website. The creators made an sdk and then you have to make your own .js file for some other functions.
While debugging I would insert a console.log(etc..) anywhere in my .js file so that I could debug object options and etc..
But I would like to be able to use the sdk as a live tool, so instead of having to edit my .js file with new console.log() lines, I'd rather just be able to type object.color_code and have the console output that string for the object color code. At the moment though it just gives me uncaught reference error, object is not defined.
I think this is because my custom .js file has all of it's script inside a $(function() { EVERYTHING }); SO, when I try to call anything in EVERYTHING from the console it says it's undefined, but if I just used console.log inside EVERYTHING it would work. So is there a way I can get around this?
Feel free to explain why it isn't working but I'd like a way to enable this, don't tell me there isn't a way, even if I have to prefix what I want with the .js file it's coming from each time, I don't mind
You were correct in that all of your variables inside the function are only being defined locally, and thus can't be accessed via the console. However, in Javascript there are at least two options for setting global variables from inside functions; If you use these to declare a variable you want to access from outside the function, it will work:
Assign a value to an undeclared variable: varname=value;
Assign the variable to the window object: window.varname=value; or window['varname']=value;
A possible workaround is to expose the object(s) that you want to debug in the global scope:
(function() {
var privateStuff = { foo: 'bar' };
// make privateStuff public for debugging purposes
window['debugObject'] = privateStuff;
})();
document.write(debugObject.foo);
If you want to expose several objects with rather common names that are likely to collide with existing ones, make sure to expose them within an object with an uncommon name rather than directly:
(function() {
var x = { str: 'this is' },
y = { str: 'a test' };
window['debugObject'] = {
x: x,
y: y
};
})();
document.write(debugObject.x.str + ' ' + debugObject.y.str);
If you're happy to change the source file then you could export whatever you want to access from EVERYTHING as a global.
$(function() {
//EVERYTHING
...
window.Ireply = window.Ireply || {};
window.Ireply.object = object;
...
});
console.log(Ireply.object); // some object
You can change a declaration like
$(function(){
var cart = {};
})
To
var cart;
$(function(){
cart = {}
})
Or
$(function(){
var cart = {};
window.cart = cart;
})
But you will want to avoid polluting global namespace. You will also want to be careful about using globals inside callbacks or loops where you can run into unexpected behaviors since local variables scope is often important to be kept local

Lightswitch HTML global JS file to pass variable

I know how this works in C#, however not so much in javascript so I am hoping it is similar.
With Javascript can I create say a master.js, with a variable (var defaultValue = "1234"), which I can reference in all other javascript files associated with the project?
so in terms of Lightswitch HTML, each screen has the ability to have a js file, and on the screen I want to be able to retrieve this defaultValue.
Can this be done?
If yes, how can I get this value onto the current screen?
so far I have created a main.js file, added this function:
function getDefaultValue(value) {
var value = "1234";
return value;
}
and declared the js file in the default.htm file:
<script type="text/javascript" src="Scripts/main.js"></script>
I know this is how i am using other JavaScript files like blob.js, lsWires.js etc...
using this method in by screen.js doesn't work so one of these stages is causing an error...
window.alert(main.getDefaultValue(value));
ideally i would like to use this defaultvalue for setting a value, i.e. var test = main.getDefaultValue(value)
This is certainly possible, and the script declaration you've used in your default.htm appears correct.
However, as the approach you've described creates a global getDefaultValue function (added to the global window object context) you wouldn't specify a main 'namespace' prefix like you would in c#.
Instead, rather than calling the function using main.getDefaultValue, you'd use the the following approach within your LightSwitch screens:
myapp.BrowseProducts.created = function (screen) {
window.alert(window.getDefaultValue("123")); // This will display 1234
// As window is a global object, its window prefix can be omitted e.g.
alert(getDefaultValue("123")); // This will display 1234
};
Or, if you want to define a global defaultValue variable in your main.js (probably the approach you're looking to implement) you would have the following code in your main.js file:
var defaultValue = "5678";
Then you'd access it as follows in your LightSwitch screens:
myapp.BrowseProducts.created = function (screen) {
alert(defaultValue); // This will display 5678
defaultValue = "Hello World";
alert(defaultValue); // This will now display Hello World
};
Also, if you'd like to organise your functions/properties in a main 'namespace', you could use the following type of approach in your main.js file: -
var main = (function (ns) {
ns.getDefaultValue = function (value) {
var value = "1234";
return value;
};
ns.defaultValue = "5678";
return ns;
})(main || {});
These would then be called as follows in your LightSwitch screens: -
myapp.BrowseProducts.created = function (screen) {
alert(main.getDefaultValue("123")); // This will display 1234
alert(main.defaultValue); // This will display 5678
main.defaultValue = "Hello World";
alert(main.defaultValue); // This will now display Hello World
};
This type of approach is covered in the following posts: -
How to span javascript namespace across multiple files?
JavaScript Module Pattern: In-Depth

Adding to ace-editor wise autocomplete: List user-defined functions and variables (javascript language)

I want to add list of user-defined functions and variables to ace editor's auto-complete.
To do it I want to examine all the code user inserted to the document, find defined functions (and their arguments), defined variables and their scope, etc.
Main question
Is that data already calculated somewhere in the ace source-code (or language-plugin) and I can just grab it in a way?`
What I want
for exapmle, if user inserted code like this:
var var0 = 'abcd';
function foo(var1, var2){
var var3 = 'efg';
}
I want to add to the auto-complete box, function called 'foo' with two parameters - var1 and var2. I want to add also var0 to variables list, and to add var3 just when user writes in the scope it's defined (in the function).
What I already knows :
I know how to enable auto-complete and live auto-complete.
I know how to add new completer
I know that built-in Basic auto-complete adding all the words in document Indiscriminately
I know about ace-tern plugin, and I don't think I want to use it. For now it's still hackish, documention-less, and I can't figure how to enable it.
I know that Ace already have some of the data I'm after. For example it warns when a variable is re-defined when already defined in the same scope. So it had list of variables and their scope. My guess it's using jshint - but Is there a way to grab it from there?
I read ace documation and find a lot useful methods I can use to extract the data, if I have to. The question is if I really need to do this myself.
UPDATE: I implied that in my answer, but to clarify - Tern will do exactly what you are asking in what i want. Snippet below solves one more problem of providing some context which you do not want user even see in the editor. See screenshots of your code used at Ace.Tern live demo
That is opionated,but imo the best option for adding auto-complete in ace is Tern.
Tern accepts typedef configuration option ( described here: http://ternjs.net/doc/manual.html#typedef), but what is more interesting, it will accept your custom js object as a child, ie:
var myContext = {
name: 'myContext',
obj: obj
}
Where obj is your js object. Then in Tern configuration you will use it as:
defs: ['underscore', myContext]
Which will use both your custom object and underscore module for autocomplete.
Tern related ace.js config: (See https://github.com/sevin7676/Ace.Tern/blob/master/demo.html for comments on config options)
var myContext = { ... }
var editor = ace.edit("editor");
editor.getSession().setUseWorker(true);
ace.config.loadModule('ace/ext/tern', function () {
editor.setOptions({
enableTern: {
defs: ['browser', 'ecma5', myContext],
plugins: {
doc_comment: {
fullDocs: true
}
},
useWorker: true,
startedCb: function () {
console.log('editor.ternServer:', editor.ternServer);
},
},
enableSnippets: true,
enableBasicAutocompletion: true,
});
});

How best to overwrite a Javascript object method

I'm using a framework that allows the include of JS files. At the top of my JS file I have something like:
<import resource="classpath:/templates/webscripts/org/mycompany/projects/library/utils.lib.js">
I want to override a fairly small method that is defined in the very large utils.lib.js file. Rather than make the change directly in utils.lib.js, a file that's part of the framework, I want to overwrite just one method. The utils.lib.js file has something that looks like:
var Evaluator =
{
/**
* Data evaluator
*/
getData: function Evaluator_getData(input)
{
var ans;
return ans;
},
...
}
I want to change just what the method getData does. Sorry for the basic question, but after importing the file which copies the JS contents into the top of my JS file, can I just do something like:
Evaluator.getData = function Mine_getData(input)
{
...
};
Yes, you can just reassign that method to your own function as you have proposed with:
Evaluator.getData = function Mine_getData(input)
{
...
};
This will successfully change what happens when the .getData(input) property is called.
Yes you can.
However Evaluator is not a proper 'class'. You can't write var x = new Evaluator();
So you are not overriding, but just changing the variable getData. That's why we say that in JavaScript, functions are first-class citizen, treated like any variable.

Categories