How to get this locale variable into the main script. How can I make a global variable from it? This variant does not work, Thanks for the help.
//Test Script local to global
(function (exampleCode) {
"use strict";
var wert = 0.5;
var name = 'wert';
Object.assign( exampleCode, {
getValue: function() {
return name;
}
} );
} )( window.exampleCode = window.exampleCode || {} );
/////////////////////////////////////////////////////////////////////
//main script get 'var wert = 0.5' from Test Script
var update = function() {
requestAnimationFrame(update);
//var value = wert; //0.5
console.log( exampleCode.getValue() );
mesh.morphTargetInfluences[ 40 ] = params.influence1 = value;
};
update();
If I understood you correctly, you need a link to the outer scope of the getValue function to get that variable. So, you can store your data in an object and then return myVars[propName]; in getValue(propName) after passing in a name for the property you would like to get. Later it will take its value (0.5) through the closure.
(function (exampleCode) {
"use strict";
let myVars = {
wert: 0.5
};
Object.assign( exampleCode, {
getValue: propName => myVars[propName]
} );
} )( window.exampleCode = window.exampleCode || {} );
let update = function() {
let value = exampleCode.getValue('wert'); //0.5
console.log( value );
//mesh.morphTargetInfluences[ 40 ] = params.influence1 = value;
};
update();
An alternative is to make wert property of exampleCode and take its value through this:
(function (exampleCode) {
"use strict";
Object.assign( exampleCode, {
getValue: function(propName) { return this[propName]; },
wert: 0.5
} );
} )( window.exampleCode = window.exampleCode || {} );
let update = function() {
let value = exampleCode.getValue('wert');
console.log( value );
};
update();
Related
As I am new to javascript, and i got a code which explains how module can be created and used but I have problem in figuring out what does the for loop does in the following snippet, So can anybody help me out
in figuring out how the code is working.
var MyModules = (function Manager() {
var modules = {};
function define(name, deps, impl) {
for (var i=0; i<deps.length; i++) {
deps[i] = modules[deps[i]];
}
modules[name] = impl.apply( impl, deps );
}
function get(name) {
return modules[name];
}
return {
define: define,
get: get
};
})();
MyModules.define( "bar", [], function(){
function hello(who) {
return "Let me introduce: " + who;
}
return {
hello: hello
};
} );
MyModules.define( "foo", ["bar"], function(bar){
var hungry = "hippo";
function awesome() {
console.log( bar.hello( hungry ).toUpperCase() );
}
return {
awesome: awesome
};
} );
var bar = MyModules.get( "bar" );
var foo = MyModules.get( "foo" );
console.log(
bar.hello( "hippo" )
);
You can read good article explain what are module how you can implement it.
https://medium.freecodecamp.org/javascript-modules-a-beginner-s-guide-783f7d7a5fcc
function myModule() {
this.hello = function() {
return 'hello!';
}
this.goodbye = function() {
return 'goodbye!';
}
}
module.exports = myModule;
You can you use the above module shown below
var myModule = require('myModule');
var myModuleInstance = new myModule();
myModuleInstance.hello(); // 'hello!'
myModuleInstance.goodbye(); // 'goodbye!'
I have a sealed object with an array member on which I want to prevent direct pushes.
var myModule = (function () {
"use strict";
var a = (function () {
var _b = {},
_c = _c = "",
_d = [];
Object.defineProperty(_b, "c", {
get: function () { return _c; }
});
Object.defineProperty(_b, "d", {
get { return _d; }
});
_b.addD = function (newD) {
_d.push(newD);
};
Object.seal(_b);
return _b;
}());
var _something = { B: _b };
return {
Something: _something,
AddD: _b.addD
};
}());
myModule.Something.c = "blah"; // doesn't update = WIN!!
myModule.AddD({}); // pushed = WIN!
myModule.Something.d.push({}); // pushed = sadness
How can I prevent the push?
UPDATE:
Thanks for all the thoughts. I eventually need the JSON to send to the server. It looks like I might need to use an object for the array then figure out a way to generate and return the JSON needed, or change _something to use .slice(). Will play and report.
you could override the push method:
var _d = [];
_d.__proto__.push = function() { return this.length; }
and when you need to use it in your module, call Array.prototype.push:
_b.addD = function (newD) {
Array.prototype.push.call(_d, newD);
};
I haven't done any performance tests on this, but this certainly helps to protect your array.
(function(undefined) {
var protectedArrays = [];
protectArray = function protectArray(arr) {
protectedArrays.push(arr);
return getPrivateUpdater(arr);
}
var isProtected = function(arr) {
return protectedArrays.indexOf(arr)>-1;
}
var getPrivateUpdater = function(arr) {
var ret = {};
Object.keys(funcBackups).forEach(function(funcName) {
ret[funcName] = funcBackups[funcName].bind(arr);
});
return ret;
}
var returnsNewArray = ['Array.prototype.splice'];
var returnsOriginalArray = ['Array.prototype.fill','Array.prototype.reverse','Array.prototype.copyWithin','Array.prototype.sort'];
var returnsLength = ['Array.prototype.push','Array.prototype.unshift'];
var returnsValue = ['Array.prototype.shift','Array.prototype.pop'];
var funcBackups = {};
overwriteFuncs(returnsNewArray, function() { return []; });
overwriteFuncs(returnsOriginalArray, function() { return this; });
overwriteFuncs(returnsLength, function() { return this.length; });
overwriteFuncs(returnsValue, function() { return undefined; });
function overwriteFuncs(funcs, ret) {
for(var i=0,c=funcs.length;i<c;i++)
{
var func = funcs[i];
var funcParts = func.split('.');
var obj = window;
for(var j=0,l=funcParts.length;j<l;j++)
{
(function() {
var part = funcParts[j];
if(j!=l-1) obj = obj[part];
else if(typeof obj[part] === "function")
{
var funcBk = obj[part];
funcBackups[funcBk.name] = funcBk;
obj[part] = renameFunction(funcBk.name, function() {
if(isProtected(this)) return ret.apply(this, arguments);
else return funcBk.apply(this,arguments);
});
}
})();
}
}
}
function renameFunction(name, fn) {
return (new Function("return function (call) { return function " + name +
" () { return call(this, arguments) }; };")())(Function.apply.bind(fn));
};
})();
You would use it like so:
var myArr = [];
var myArrInterface = protectArray(myArr);
myArr.push(5); //Doesn't work, but returns length as expected
myArrInterface.push(5); //Works as normal
This way, you can internally keep a copy of the interface that isn't made global to allow your helper funcs to modify the array as normal, but any attempt to use .push .splice etc will fail, either directly, or using the .bind(myArr,arg) method.
It's still not completely watertight, but a pretty good protector. You could potentially use the Object.defineProperty method to generate protected properties for the first 900 indexes, but I'm not sure of the implications of this. There is also the method Object.preventExtensions() but I'm unaware of a way to undo this effect when you need to change it yourself
Thank you, dandavis!
I used the slice method:
var myModule = (function () {
"use strict";
var a = (function () {
var _b = {},
_c = _c = "",
_d = [];
Object.defineProperty(_b, "c", {
get: function () { return _c; }
});
Object.defineProperty(_b, "d", {
get { return _d.slice(); } // UPDATED
});
_b.updateC = function (newValue) {
_c = newValue;
};
_b.addD = function (newD) {
_d.push(newD);
};
Object.seal(_b);
return _b;
}());
var _something = { B: _b };
return {
Something: _something,
AddD: _b.addD
};
}());
myModule.Something.c = "blah"; // doesn't update = WIN!!
myModule.AddD({}); // pushed = WIN!
myModule.Something.d.push({}); // no more update = happiness
This allows me to protect from direct push calls enforcing some logic.
I set up some event listeners in a traditional way like this:
<script>
window.onload = setup;
function(setup) {
var myButton = document.getElementById("myButton");
myButton.onclick = someFunction;
}
What I want someFunction to do is to change a certain variable inside my code (when the button is pushed of course). Let's say for example, that I have a function something() in my code containing variable x and the event listener is active.
function something() {
var x;
for (;;) {
if (x === value set by someFunction) {
break;
}
}
}
How can I do that?
When an event is fired you can do stuff so:
CODE CODE CODE
....
var x = INITIAL_VALUE;
function someFunc(){
x = what ever you wish;
}
The simple way is to make x a global variable.
If you don't want to pollute the global namespace, you use an immediately executing function:
(function() {
var x;
function someFunc() {
// May assign x
}
function setup() {
var myButton = document.getElementById("myButton");
myButton.onclick = someFunction;
}
window.onload = setup;
function something() {
// Use x
}
})();
This function creates a local namespace for the x variable.
If I understand your question, the simplest way would be to define a global variable var value, such that it would be accessible by both someFunction() and by something().
Another approach, without any listener, could be:
function something() {
var x;
for (;;) {
if (x === someFunction()) {
break;
}
}
}
function someFunction() {
...
return value;
}
//
// try a 'notifier' decorator
//
function notifier( handler_fn, callback_fn ) {
// #helpers
function slc( args, i1, i2 ) {
return Array.prototype.slice.call( args, i1, i2 );
}
function prepend( targetArr, arr ) {
Array.prototype.unshift.apply( targetArr, arr );
return targetArr;
}
function thepush( targetArr, arr ) {
Array.prototype.push.apply( targetArr, arr );
return targetArr;
}
return ( function( cb, args1 ) {
var origfn = this;
return function() {
var
args = prepend( slc( arguments ), args1 ),
out = origfn.apply( this, args );
cb.apply( this, thepush( args, [out] ) );
return out;
};
} ).call( handler_fn, callback_fn, slc( arguments, 2 ) );
}
var
handlerfn = function ( e ) {
var
T = e.type.toUpperCase();
( this instanceof Node ) && ( this.innerHTML = T );
return T;
},
F = notifier(
handlerfn,
function ( f1_in, f1_out ) {
var
v1 = f1_in;
v1.target.innerHTML += ', coords:[' + v1.clientX + ', ' + v1.clientY +']';
console.log( f1_in, ', ', f1_out );
}
);
document.getElementById('btn_01').onclick = F;
//
//
Hi I am using phonegap to develop a shopping app. I want to give the user an option to save their order and complete wheneven he/she finds convenient. My question where do I save the order data. Local file system or local db of the mobile device? I will like to save the order
in json format in a local file. Please suggest the best option for me. Also a snippet will be highly appreciated. Thanks
You could also use HTML5 localStorage as an easier alternative to file storage. I have been using an encapsulated version of localStorage to facilitate get/set operations and decrease namespace pollution. Please see code base below:
/**
* The class is designed to facilitate flexible permanent storage of key value
* pairs utilzing HTML5 localStorage.
*
* #class LocalMap
* #author Zorayr Khalapyan
* #version 10/25/2012
*/
var LocalMap = function ( name ) {
var that = {};
//Prevent compatability issues in different execution environments.
if ( !localStorage ) {
localStorage = {};
}
if ( !localStorage[name] ) {
localStorage[name] = "{}";
}
var setMap = function ( map ) {
localStorage[name] = JSON.stringify( map );
};
that.getMap = function () {
return JSON.parse( localStorage[name] );
};
/**
* Stores the specified (key, value) pair in the localStorage
* under the map's namespace.
*/
that.set = function ( name, object ) {
var map = that.getMap();
map[ name ] = object;
setMap( map );
};
that.get = function ( name ) {
var map = that.getMap();
return typeof( map[ name ] ) !== "undefined" ? map[name] : null;
};
that.importMap = function ( object ) {
var map = that.getMap();
var key;
for ( key in object ) {
if (object.hasOwnProperty(key)) {
map[key] = object[key];
}
}
setMap(map);
};
that.length = function () {
var map = that.getMap();
var size = 0, key;
for (key in map) {
if (map.hasOwnProperty(key)) size++;
}
return size;
};
that.erase = function () {
localStorage[name] = JSON.stringify({});
};
that.isSet = function (name) {
return that.get(name) != null;
};
that.release = function (name) {
var map = that.getMap();
if (map[name]) {
delete map[name];
}
setMap(map);
};
that.deleteNamespace = function(){
if (localStorage.hasOwnProperty(name)) {
delete localStorage[name];
}
};
return that;
};
LocalMap.destroy = function () {
for ( var item in localStorage ) {
if ( localStorage.hasOwnProperty( item ) ) {
delete localStorage[ item ];
}
}
};
LocalMap.exists = function (name) {
return (localStorage[name]) ? true : false;
};
Below are the unit tests for get and set functions:
test( "Test set()", function() {
var map = LocalMap('test-namespace');
///
map.set("var-1", "val-1");
map.set("var-2", "val-2");
map.set("var-3", "val-3");
//
ok(map.isSet("var-1"), "A variable should be successful set.");
ok(map.isSet("var-2"), "A variable should be successful set.");
ok(map.isSet("var-3"), "A variable should be successful set.");
});
test( "Test get()", function() {
var map = LocalMap('test-namespace');
map.set("var-1", "val-1");
map.set("var-2", "val-2");
map.set("var-3", "val-3");
///
var var1 = map.get("var-1");
var var2 = map.get("var-2");
var var3 = map.get("var-3");
var var4 = map.get("var-4");
//
equal(var1, "val-1", "A set variable should be succesfully retreived.");
equal(var2, "val-2", "A set variable should be succesfully retreived.");
equal(var3, "val-3", "A set variable should be succesfully retreived.");
equal(var4, null, "A variable that was not set should not be retreived.");
});
Hope this helps, and let me know if you have any questions.
How about the below code? I copied it from here. Actually I like its code.
// define dbContext & entities------------------------------------
var DemoDataContext = function () {
nova.data.DbContext.call(this, "Demo", "1.0", "Demo DB", 1000000);
this.users = new nova.data.Repository(this, User, "users");
this.roles = new nova.data.Repository(this, Role, "roles");
};
DemoDataContext.prototype = new nova.data.DbContext();
DemoDataContext.constructor = DemoDataContext;
var User = function () {
nova.data.Entity.call(this);
this.name = "";
this.password = "";
this.birthYear = 1980;
this.createdDate = new Date();
this.deleted = false;
};
User.prototype = new nova.data.Entity();
User.constructor = User;
var Role = function () {
nova.data.Entity.call(this);
this.name = "";
this.createdDate = new Date();
};
Role.prototype = new nova.data.Entity();
Role.constructor = Role;
// end define dbContext & entities------------------------------------
// service methods----------------------------------------------------
function getAllUsers(callback) {
new DemoDataContext().users.toArray(function (users) {
alert(users.length);
callback(users);
});
}
function getUserByName(name, callback) {
new DemoDataContext().users.where("name='" + name + "'").toArray(function (users) {
callback(users.firstOrDefault());
});
}
function addRole(roleName, callback) {
var role = new Role();
role.name = roleName;
var db = new DemoDataContext();
db.roles.add(role);
db.saveChanges(callback);
}
function updateUserPassword(username, password, callback) {
getUserByName(username, function (user) {
if (user == null) {
throw "no user found.";
}
user.password = password;
var db = new DemoDataContext();
db.users.update(user);
db.saveChanges(callback);
});
}
function deleteUserByName(name, callback) {
getUserByName(name, function (user) {
if (user == null) {
throw "no user found.";
}
var db = new DemoDataContext();
db.users.remove(user);
db.saveChanges(callback);
});
}
// end service methods----------------------------------------------------
function Foo() {
var myPrivateBool = false,
myOtherVar;
this.bar = function(myOtherVar) {
myPrivateBool = true;
myOtherVar = myOtherVar; // ?????????????????
};
}
How can I set the private variable myOtherVar?
Give the parameter a different name:
function Foo() {
var myPrivateBool = false,
myOtherVar;
this.bar = function( param ) {
myPrivateBool = true;
myOtherVar = param;
};
this.baz = function() {
alert( myOtherVar );
};
}
var inst = new Foo;
inst.bar( "new value" );
inst.baz(); // alerts the value of the variable "myOtherVar"
http://jsfiddle.net/efqVW/
Or create a private function to set the value if you prefer.
function Foo() {
var myPrivateBool = false,
myOtherVar;
function setMyOtherVar( v ) {
myOtherVar = v;
}
this.bar = function(myOtherVar) {
myPrivateBool = true;
setMyOtherVar( myOtherVar );
};
this.baz = function() {
alert(myOtherVar);
};
}
var inst = new Foo;
inst.bar("new value");
inst.baz();
http://jsfiddle.net/efqVW/1/
In JavaScript it is a convention to prefix the name of private variables with an _ (underscore).
Following this convention you can change your code to.
function Foo() {
var _myPrivateBool = false,_myOtherVar;
this.bar = function(myOtherVar) {
_myPrivateBool = true;
_myOtherVar = myOtherVar;
};
}
In the above code we are assigning the local variable myOtherVar to the private variable _myOtherVar.
This way it looks like we have the same name for the private and local variables.
Note:This is just a convention followed.Prefixing a variable name with _ does not make it a private variable.
I think this.myOthervar = myOtherVar; will corrupt the global namespace and created a variable window.myOtherVar in window object
Try this.myOtherVar = myOtherVar;
Maybe you can declare myOtherVar as MyOtherVar, taking advantage of javascript's case sensitiveness, then assign MyOtherVar=myOtherVar into the function:
function Foo() {
var MyPrivateBool = false,
MyOtherVar;
this.bar = function(myOtherVar) {
MyPrivateBool = true;
MyOtherVar = myOtherVar;
};
}