EmberJS, jQuery UI, and Grunt. - javascript

I am integrating Emberjs and jquery ui. using the methods mentioned in http://www.lukemelia.com/blog/archives/2012/03/10/using-ember-js-with-jquery-ui/
Everything thing seems to be working ok.
The problem is following:
When I have
JQ = {};
to declare a new namespace I faced with this error (although it works fine on the browser)
JQ is not defined
when I declare the same variable as
var JQ = {};
Grunt shows no errors but it stops working in the browser.
I looked into the combined code in the browsers it is like the following
function(){
var JQ = {};
}
....rest of the code
so I am sure it is declared but the browser don't mange to see it.
So I can't find out the problem? nor the solution
Best,
Mohammad

if you want to make JQ global..declare it as window.JQ = {}
i think issue may be just linting....add JQ to the globals...
In orderto make sure jshint doesnt throw error..add JQ to the global list in .jshintrc file

When you use var JQ = {}; and the result is
function(){
var JQ = {};
}
your variable is defined only in the scope of that function, which means that you can't use it outside of that closure. So, when you use JQ = {}; your compiled file should contain:
function(){
JQ = {};
}
which defines the variable in the global namespace. But you said that you got JQ is not defined, so I could suggest to check if you don't use the variable before its definition.

Related

What is the benefit of this JavaScript pattern based on an IIFE?

I master the Javascript IIFE essence, but while reading this page, I'm kinda confused of the usage.
It sounds that the following JavaScript pattern is pretty common:
(function(something) {
something.foo = 123;
})(something || something = {})
A usage example:
(function(something) {
something.foo = 123;
})(something || something = {})
console.log(something); // {foo:123}
(function(something) {
something.bar = 456;
})(something || something = {})
console.log(something); // {foo:123, bar:456}
As something is defined in the global scope, what is the benefit of this pattern in relation to the following trivial code:
var something;
something.foo = 123;
something.bar = 456;
Which use case would it make sense to use it?
You get a closure over something which ensured that even though some other code overrides it's in global scope you will still have the right reference to that something, it's better illustrated with jQuery and jQuery.noConflict();:
<script src="/path/to/jquery.js"></script>
<script>
(function($) {
// Here $ is jQuery
// Something asynchrone is happening:
setTimeout(function() {
// But $ is still jQuery
}, 1000);
})($);
</script>
<script>
// Someone calls jQuery.noConflict();
jQuery.noConflict();
// And now $ is not jQuery
</script>
Lets say you have a namespace for your application myApp. You have several scripts that add functionality because like a good developer you've broken your application up into different chunks. Also like a good web developer you're loading those scripts asynchronously, you don't know what order they are going to be added in. So you have each module conditionally create the namespace for the app if it doesn't exist (the (myApp || {}) part). You also want to hide the internal functionality of the module from stuff that doesn't need to know about it, so you pass your 'namespace' object into a function that creates a closure and attaches the module's API to the namespace object myApp.
// async loaded script for the foo 'module'
(function(myApp) {
var myPrivate = 3; // hidden in the closure
myApp.getFoo = function() { return myPrivate; };
}(myApp || {});
This pattern is not without its flaws (what if myApp.foo depends on myApp.bar?) which is why its largely been replaced by browserify/require.js/webpack/etc.

JS namespace Netbeans variable not declared

When I was defining a namespace in JavaScript, Netbeans gave a global variable not declared error while I think it shouldn't. Why is this?
Demonstration code:
var MyNamespace = new function () {
var MyClass = function () {};
MyClass.SOME_CONSTANT = 9; // MyClass not defined
this.MyClass = MyClass; // MyClass not defined
};
I checked and this code works in IE (document mode IE 5) and Edge 13. The code is a Module Pattern like syntax like in this answer.
EDIT: first declaring a variable is probably not useful, for a function inside the namespace will sometimes change the local variable instead of that in the public namespace, am I right? Still, I wonder why Netbeans gives me an error.
You can add a comment to the top which will tell Netbeans to ignore the error.
For example when using angular
/* global angular */
Will prevent the error for things like
angular.module('Module', []);
I am using NetBeans IDE 8.2 (Build 201705191307)
If you want to completely ignore this type of error, I would suggest this:
Tools > Options > Editor > Hints > Uncheck "The global variable is not declared"
It worked for me.

Disable editing of javascript from chrome console?

So, I just noticed today that you can apparently run javascript in the chrome console. I had no idea you could do this. It's actually really cool.
In my rails app, I have an external javascript page. Some of the variables on that page I would like to be global so that all the functions in the JS file can access them. for example I have a map, and I would like the map object to be global in the javascript file because that way all my functions access the one map variable instead of creating their own, and I can break complex operations down into smaller functions.
This is all well and good I know how to do that and it's working perfectly. My problem now, can I protect the variables from outside? For example you can change the values of all the javascript class variables from the chrome console.. as well methods from for example the map are accessible and excecutable.. I have locked the map settings on one of the pages so it is not zoomable or movable, however from the console I can simply say map.setZoom(11) and the map will zoom to 11.. I can type map.dragable = true and bam u can drag the map.. I don't like this really..
It's not too terribly bad yet like the user enabling map drag and zoom isnt the worst thing in the world.. but still I'd like to disable this. Any ideas?
EDIT
Thanks all for the answers and comments. I guess I will just resort to not putting anything that can be turned malicious into my javascript, and do thing like pass my map variable to functions where necessary to slow people down.
You can use an immediately-invoked function (IIFE) expression to prevent your variables and functions from being exposed in the global scope:
var a = 10;
(function() {
var b = 20;
})();
window.a lets you view and modify a, but you cannot do that with b:
Try it out here
I'm more than sure that there's a way to edit b with Inspector, but I haven't taken the time to figure it out. Don't waste your time trying to prevent your users from modifying code that they can view.
You can't. Even if you wrap them into anonymous functions, user can get to them through debugger. As last resort he can simply intercept your traffic to his own machine and replace your JavaScript with something else.
Bottom line: JavaScript in browser is client-side. Client can do whatever he pleases with it.
Try doing something like this:
(function(){
//All of your current code
})();
One thing to still be aware of - Chrome developer tools also lets you edit the javascript (not the javascript file on the server, just currently running copy.) Go to Chrome Dev Tools->Sources and you can edit the javascript files.
You can't. Your saying you need to define your map globally, this means it's accessible for everyone.
You could define your map in a different scope and then only define the "public" things:
(function() {
var map = new Map();
window.myMap = {
goTo: function(lat, lng) {
map.goTo(lat, lng);
}
};
})();
Depending on your architecture, there are a few ways to accomplish this. Use this method to create a reusable component that has public and private properties:
var protectedScope = function () {
var protected_var = 'protected';
this.showProtected = function () {
return protected_var;
}
this.public = 'public';
};
var myObject = new protectedScope();
console.log('Public var: '+myObject.public); // outputs "public"
console.log('Protected via accessor: '+myObject.showProtected ()); // outputs "private"
console.log('Protected var: '+myObject.protected); // outputs undefined
Any variable or function declared with a var keyword will be, in effect, private. Any variable or function that uses the this.name mechanism will be "public".
Understand that this structure is not truly public or private, such concepts are not a part of the language. There are still ways to get at those variables, and one can always view source. Just be clear; this is a code organization concept rather than a security concept. Chrome has had this developer console for a while, and other major user agents are moving to include similar tools (or already have done so). There are also tools like Firebug which allow a user full access to your javascript runtime environment. This isn't a realm that the developer can control at all.
Try it here: http://jsfiddle.net/cf2kS/
More Reading
"Private Members in JavaScript" by Douglas Crockford* - http://www.crockford.com/javascript/private.html
"OOP in JS, Part 1 : Public/Private Variables and Methods" on http://phrogz.net - http://phrogz.net/JS/classes/OOPinJS.html
Javascript Object Management on MDN - https://developer.mozilla.org/en-US/docs/XUL_School/JavaScript_Object_Management
Closures on MDN - https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures
Object.defineProperty(map, 'zoom', {value:1});
or
Object.defineProperty(map, 'zoom',{
set: function(){console.warn('Access denied!');},
get: function(){return 1;}
});
demo
or
Object.defineProperty(Object.prototype, 'protect', {
value: function(ignore){
var childObjects = [], ignore = ignore || [];
ignore.push(this);
if(this instanceof MimeType)return; //Chrome Fix //window.clientInformation.mimeTypes[0].enabledPlugin[0] !== window.clientInformation.mimeTypes[0]
for(var prop in this){
if(typeof this[prop] === "unknown")continue; //IE fix
if(this[prop] instanceof Object){
var skip = false;
for(var i in ignore)
if(ignore[i]===this[prop]){
skip = true;
break;
}
if(!skip)childObjects.push(prop);
}
var d = Object.getOwnPropertyDescriptor(this, prop);
if(!d || !d.configurable || !d.writable)continue;
var that = this;
(function(){
var temp = that[prop];
delete that[prop];
Object.defineProperty(that, prop,{
set: function(){console.warn('Access denied!');},
get: function(){return temp;}
});
})();
}
for(var i = 0;i<childObjects.length;i++)
this[childObjects[i]].protect(ignore);
}
});
this.onload=function(){this.protect();} //example
demo

Invoking JavaScript "new" from CoffeeScript

I am trying to reuse a JavaScript library (sim.js) in CoffeeScript code. In an example that comes with sim.js, there are 3 files, "sim-0.26.js", "buffet_restaurant.js", and "buffet_restaurant.html" wired together like this (I've eliminated some parameters to simplify):
Inside of "buffet_restaurant.html", there is
<script type="text/javascript" src="./buffet_restaurant_files/sim-0.26.js"></script>
<script type="text/javascript" src="./buffet_restaurant_files/buffet_restaurant.js"></script>
<script type="text/javascript">
$(function () {
$("#run_simulation").click(function () {
var results = buffetRestaurantSimulation();
...
where buffetRestaurantSimulation is a function inside of buffet_restaurant.js. The code in buffet_restaurant.js starts off like this:
function buffetRestaurantSimulation()
{
var sim = new Sim();
...
where Sim is defined in sim-0.26.js, like this:
function Sim(){...};
This example runs fine. I want to reuse "Sim" in a CoffeeScript file in node.js. So I try this (invoked from jasmine-node):
sjs = require "./sim-0.26.js"
mysim = new sjs.Sim()
where sim-0.26.js is in the same directory as testsim.spec.coffee, the file containing this code. When I invoke this using:
jasmine-node --coffee ./testsim.spec.coffee
I get this:
mysim = new sjs.Sim();
^
TypeError: undefined is not a function
I suspect I am doing a ton of things wrong. I'm pretty new to all this.
Any ideas?
Unless Sim is added to exports it will not be available when required - see the docs on modules for more information on the way Node.js modules need to be written.
If this needs to work in both the browser and in node, then simply add this to the code for sim.js:
var root = typeof exports === "object" ? exports : window;
root.Sim = Sim;

How to use a JavaScript method/object that has been defined in another file?

I have a some JavaScript with a complex structure. Because I'm new comer to JavaScript (only understanding some basic concepts) I don't know how to use it properly.
I have two files : Circle.js and Line.js. In Circle.js, I want to use a class object defined in Line.js:
In file Circle.js :
Helper.using('py.Figures', function (ns) {
ns.Circle = function (params) {
// some additional methods and code here
}
}
And in Line.js is :
Helper.using('py.Figures', function (ns) {
ns.Line2Point = function (params) {
// some addition methods and code here
};
}
In Figures.Circle, in ns.Circle I want to use Line2Point but I don't know how.
I think it should be :
line = new ns.Line2Point(params);
But It seem doesn't work.
According to Helper Class, ns will point to helper.using, in this case py.Figures. Does it mean, ns is the same object/reference in both the files?
I don't think this is doable in Javascript directly across files. If they are part of the same namespace you could share some 'global' objects to achieve this have the line2points and circles attach themselves to that global object:
Ex:
var myShapesNameSpace = {};
Circle.js:
(function(){
var circle = {};
circle.method1 = function(){...}
circle.method2 = function(){...}
myShapesNameSpace.Circles = circle;
})(window.myShapesNameSpace = window.myShapesNameSpace || {}); //check if namespace object exists. Else create a new blank one.
Line.js:
(function(){
var line= {};
line.method1 = function(){...}
line.method2 = function(){...}
myShapesNameSpace.Lines= line;
})(window.myShapesNameSpace = window.myShapesNameSpace || {});
Now you can check for the existence of myShapesNameSpace.Circles or .Lines and call the corresponding methods accordingly.
You can include files in javascript and reference objects across files unless they are exported in some global form either via window or your define global
Welcome to Javascript, the shit parts. Require.js was designed precisely for this because the creators of JS, well, I guess thought that everyone would write every program in one file.
RequireJS
It was designed for web use but can be used elsewhere too (locally, with Node, etc.)

Categories

Resources