Declare global jquery objects - javascript

Below is some typical jquery that I'm working with. As you will see, variables are declared at a global scope (excuse the terminology), however, I wondered if it was also possible to declare a jquery objects the same way that cn, declares class names.
For instance: var jq = { $html : $('html')};
I haven't managed to get any type of syntax to work as yet.
Thanks in advance.
var Nav = function () {
var pub = {},
cn = {
open: "mobile-nav-open"
};
function toggleNav(e) {
e.preventDefault();
$html = $('html');
if ($html.hasClass(cn.open)) {
$html.removeClass(cn.open);
} else {
$html.addClass(cn.open);
}
};
function setupBindings() {
$(document).on("click", "#navicon", toggleNav);
};
pub.init = function () {
setupBindings();
};
return pub;
} ();

jQuery objects are just a class of JavaScript object. There's nothing special about them.
The syntax is the same as your existing code.
Use a : where you have a = inside your object literal.

Javascript object uses name-value pairs. if you declare any anonymous variable inside an object, that context of that variable would be the object
var hellow = 'hh'
var x = {
hellow: 'abc'
}
console.log(hellow)
console.log(x.hellow)

Related

Javascript executing function with a string

I'm creating a prototype class like so, but I want to call a function using a string as the function name. I found the windowname; example somewhere, but it's not working in my case.
function someObj() {
this.someMethod = function() {
alert('boo');
name = "someOtherMethod";
window[name]();
}
var someOtherMethod = function() {
alert('indirect reference');
}
}
This is because "someOtherMethod" is not a member of the window object as it defined inside the someObj function.
window is only for global variables.
You can't access local variables via a string, unles you use eval, which is almost always a bad idea.
One alternate way is to use an object. This allows you to look up properties using a string.
function someObj() {
var methods = {};
methods.someMethod = function() {
alert('boo');
var name = "someOtherMethod";
methods[name]();
}
methods.someOtherMethod = function() {
alert('indirect reference');
}
}
someOtherMethod is hidden from window and exists only in the scope of your prototype.
Try to move it out.
function someObj() {
this.someMethod = function() {
alert('boo');
name = "someOtherMethod";
window[name]();
}
}
var someOtherMethod = function() {
alert('indirect reference');
}
Although it is a bad idea using globals.
Create your own hash of methods:
function someObj() {
this.someMethod = function() {
alert('boo');
name = "someOtherMethod";
methods[name]();
}
var methods = {
someOtherMethod : function() {
alert('indirect reference');
}
};
}
Your variable is local to your function so it won't be in window. Even if you are working in the global scope, it is better to use your own object than it is to rely on window so you can avoid name collisions.

Basic javascript code layout

I have what I think is a fairly simply question but it's one that I can not find the answer to. I have a objects literal that I have created that groups functions, I want to know how I can create a variable that is inside the objects literal and editable/accessable by all the functions within that objects literal. At the moment the only way I know how to do this is create a global variable but I want to stop populating the global in this way. To better describe what I'm looking fiddle
http://jsfiddle.net/aT3J6/
Thanks, for any help.
var clickCount = 0;
/* I would like to place clickCount inside hideShowFn Object but all function inside need access to it, so global within hideShowFn */
hideShowFn = {
init:function(){
$('.clickMe').click(this.addToCount);
},
addToCount:function(){
clickCount++;
$('<p>'+ clickCount + '</p>').appendTo('body');
}
}
hideShowFn.init();
Create a function which is invoked immediately and returns the object, with the private variable inside the function, like this:
var obj = (function () {
var privateStuff = 'private';
return {
func1: function () {
//do stuff with private variable
},
func2: function () {
//do stuff with private variable
}
};
}());
http://jsfiddle.net/BE3WZ/
This is the way to have private variables in Functional Programming.
http://jsfiddle.net/mattblancarte/aT3J6/10/
Another option would be the pseudo-classical style:
function Constructor(){
var private = 'private';
this.public = 'public';
this.methods = {
//your methods here...
};
}
var obj = new Constructor();
Don't forget to use the 'new' keyword, or else you are going to be globally scoped.
Your code translated to this style would be:
function Test(){
var that = this,
clickCount = 0;
this.init = function(){
$('.clickMe').click(this.addToCount);
};
this.addToCount = function(){
clickCount++;
$('<p>'+ clickCount + '</p>').appendTo('body');
};
}
var test = new Test();
test.init();
You can make a closure as Cokegod says or you can simply add the variable to the object and access it using this
hideShowFn = {
clickCount: 0,
init:function(){
$('.clickMe').click(this.addToCount);
},
addToCount:function(){
this.clickCount++;
$('<p>'+ this.clickCount + '</p>').appendTo('body');
}
}
hideShowFn.init();
This dosn't work as Musa says the scope in addToCount will be the dom node clicked.
But see Cokegod's answer.

Sharing variables in JavaScript Namespace

My Goal: To namespace my javascript to keep the global namespace clean.
My question: how do I share variables between methods in my JavaScript namespace?
In my example I am extending and overwriting the behaviour of the ASP.net ModalPopupExtender. I want to know how I can share the modalPopupStack variable with ModalPopupShowOverride and ModalPopupHideOverride without making it global.
Relevant code:
$(function () {
if (Sys.Extended != undefined && Sys.Extended.UI != undefined && Sys.Extended.UI.ModalPopupBehavior != undefined) {
MyPageMethods.ModalPopupShowOriginal = Sys.Extended.UI.ModalPopupBehavior.prototype.show;
MyPageMethods.ModalPopupHideOriginal = Sys.Extended.UI.ModalPopupBehavior.prototype.hide;
Sys.Extended.UI.ModalPopupBehavior.prototype.show = MyPageMethods.ModalPopupOverrides.ModalPopupShowOverride;
Sys.Extended.UI.ModalPopupBehavior.prototype.hide = MyPageMethods.ModalPopupOverrides.ModalPopupHideOverride;
}
});
var MyPageMethods = {
ModalPopupShowOriginal: function () { },
ModalPopupHideOriginal: function () { },
ModalPopupOverrides: {
modalPopupStack: new Array(),
ModalPopupShowOverride: function () {
var extender = this;
var topElement;
MyPageMethods.ModalPopupShowOriginal.apply(this, arguments);
for (var x = 0; x < modalPopupStack.length; x++) {
if ($(modalPopupStack[x].background).css("z-index") > $(extender._element).css('z-index') || $(modalPopupStack[x].popup).css("z-index") > $(extender._element).css('z-index')) {
if ($(modalPopupStack[x].background).css("z-index") > $(extender._element).css('z-index')) {
topElement = $(modalPopupStack[x].background).css("z-index");
}
else if ($(modalPopupStack[x].popup).css("z-index") > $(extender._element).css('z-index')) {
topElement = $(modalPopupStack[x].popup).css("z-index");
}
}
}
if (topElement != undefined) {
$(extender._backgroundElement).css('z-index', topElement);
}
modalPopupStack.push({ 'id': extender._id, 'background': extender._backgroundElement, 'popup': extender._element });
},
ModalPopupHideOverride: function () {
var extender;
MyPageMethods.ModalPopupHideOriginal.apply(this, arguments);
extender = modalPopupStack.shift();
}
}
}
I'm sure there is a simple solution to this, but I'm not sure what it is.
It sounds like you want the variables to be visible within your namespace but not outside of it. If so then try the following solution.
var MyPageMethods = (function() {
// This variable is local to the namespace. It can't be accessed from
// the caller
var modalPopupStack = new Array();
// These values are available to the callers as members of MyPageMethods
return {
ModalPopupShowOriginal: function () { },
ModalPopupHideOriginal: function () { },
ModalPopupOverrides: { ... }
};
})();
This pattern uses a function to establish a private function scope for local variables of the namespace. It then returns a new object which contains the members accessible outside the namespace. Those definitions occur inside the function hence they can access the namespace private data.
You can reference that property in both methods using:
MyPageMethods.ModalPopupOverrides.modalPopupStack
That can be a little bit cumbersome, so you'd likely want to alias it inside each method, like this:
var modalPopupStack = MyPageMethods.ModalPopupOverrides.modalPopupStack;
Note that the value is still visible in the global scope (unlike in #JaredPar's answer), but its merely piggy-backing on an existing global object.
Make it part of the namespace, if you like. Or for more privacy, make a local closure which incorporates it and exposes the functions you want:
var MyPageMethods = {
ModalPopupShowOriginal: function () { },
ModalPopupHideOriginal: function () { },
ModalPopupOverrides: (function() {
var modalPopupStack = new Array();
var show = function () {
// show implementation using modalPopupStack
};
var hide = function () {
// hide implementation using modalPopupStack
};
return {
ModalPopupShowOverride: show,
ModalPopupHideOverride: hide
}
}())
};
By the way, it's pretty rare to use new Array() these days. This is usually preferred:
var modalPopupStack = [];
It's shorter, cleaner, and really more explicit.

Is it possible to append functions to a JS class that have access to the class's private variables?

I have an existing class I need to convert so I can append functions like my_class.prototype.my_funcs.afucntion = function(){ alert(private_var);} after the main object definition. What's the best/easiest method for converting an existing class to use this method? Currently I have a JavaScript object constructed like this:
var my_class = function (){
var private_var = '';
var private_int = 0
var private_var2 = '';
[...]
var private_func1 = function(id) {
return document.getElementById(id);
};
var private_func2 = function(id) {
alert(id);
};
return{
public_func1: function(){
},
my_funcs: {
do_this: function{
},
do_that: function(){
}
}
}
}();
Unfortunately, currently, I need to dynamically add functions and methods to this object with PHP based on user selected settings, there could be no functions added or 50. This is making adding features very complicated because to add a my_class.my_funcs.afunction(); function, I have to add a PHP call inside the JS file so it can access the private variables, and it just makes everything so messy.
I want to be able to use the prototype method so I can clean out all of the PHP calls inside the main JS file.
Try declaring your "Class" like this:
var MyClass = function () {
// Private variables and functions
var privateVar = '',
privateNum = 0,
privateVar2 = '',
privateFn = function (arg) {
return arg + privateNum;
};
// Public variables and functions
this.publicVar = '';
this.publicNum = 0;
this.publicVar2 = '';
this.publicFn = function () {
return 'foo';
};
this.publicObject = {
'property': 'value',
'fn': function () {
return 'bar';
}
};
};
You can augment this object by adding properties to its prototype (but they won't be accessible unless you create an instance of this class)
MyClass.prototype.aFunction = function (arg1, arg2) {
return arg1 + arg2 + this.publicNum;
// Has access to public members of the current instance
};
Helpful?
Edit: Make sure you create an instance of MyClass or nothing will work properly.
// Correct
var instance = new MyClass();
instance.publicFn(); //-> 'foo'
// Incorrect
MyClass.publicFn(); //-> TypeError
Okay, so the way you're constructing a class is different than what I usually do, but I was able to get the below working:
var my_class = function() {
var fn = function() {
this.do_this = function() { alert("do this"); }
this.do_that = function() { alert("do that"); }
}
return {
public_func1: function() { alert("public func1"); },
fn: fn,
my_funcs: new fn()
}
}
var instance = new my_class();
instance.fn.prototype.do_something_else = function() {
alert("doing something else");
}
instance.my_funcs.do_something_else();
As to what's happening [Edited]:
I changed your my_funcs object to a private method 'fn'
I passed a reference to it to a similar name 'fn' in the return object instance so that you can prototype it.
I made my_funcs an instance of the private member fn so that it will be able to execute all of the fn methods
Hope it helps, - Kevin
Maybe I'm missing what it is you're trying to do, but can't you just assign the prototype to the instance once you create it? So, first create your prototype object:
proto = function(){
var proto_func = function() {
return 'new proto func';
};
return {proto_func: proto_func};
}();
Then use it:
instance = new my_class();
instance.prototype = proto;
alert(instance.prototype.proto_func());

Encapsulation in javascript

I need to create simple reusable javascript object publishing several methods and parameterized constructor. After reading through several "OOP in JavaScript" guides I'm sitting here with an empty head. How on the Earth can I do this?
Here my last non-working code:
SomeClass = function(id) {
this._id = id;
}
(function() {
function intFun() {
return this._id;
}
SomeClass.prototype.extFun = function() {
return incFun();
}
})();
This is my usual approach:
MyClass = function(x, y, z) {
// This is the constructor. When you use it with "new MyClass(),"
// then "this" refers to the new object being constructed. So you can
// assign member variables to it.
this.x = x;
...
};
MyClass.prototype = {
doSomething: function() {
// Here we can use the member variable that
// we created in the constructor.
return this.x;
},
somethingElse: function(a) {
}
};
var myObj = new MyClass(1,2,3);
alert(myObj.doSomething()); // this will return the object's "x" member
alert(myObj.x); // this will do the same, by accessing the member directly
Normally the "this" keyword, when used in one of the object's methods, will refer to the object itself. When you use it in the constructor, it will refer to the new object that's being created. So in the above example, both alert statements will display "1".
An exception to this rule is when you pass one of your member functions somewhere else, and then call it. For example,
myDiv.onclick = myObj.doSomething;
In this case, JavaScript ignores the fact that "doSomething" belongs to "myObj". As a result, the "this" inside doSomething will point to another object, so the method won't work as expected. To get around this, you need to specify the object to which "this" should refer. You can do so with JavaScript's "call" function:
myDiv.onclick = function() {
myObj.doSomething.call(myObj);
}
It's weird, but you'll get used to it eventually. The bottom line is that, when passing around methods, you also need to pass around the object that they should be called on.
I usually don't worry too much about hiding the internals, although I do prefix them with underscores to mark them as not intended to be used outside the "class". Normally what I will do is:
var MyClass = function() {};
MyClass.prototype = {
_someVar : null,
_otherVar : null,
initialize: function( optionHash ) {
_someVar = optionsHash["varValue"];
_otherVar = optionsHash["otherValue"];
},
method: function( arg ) {
return _someVar + arg;
},
};
And use it as so...
var myClass = new MyClass( { varValue: -1, otherValue: 10 } );
var foo = myClass.method(6);
All vars are private:
SomeClass = function (id) {
var THIS = this; // unambiguous reference
THIS._id = id;
var intFun = function () { // private
return THIS._id;
}
this.extFun = function () { // public
return intFun();
}
}
Use THIS within private methods since this won't equal what you might expect.
From http://learn.jquery.com/code-organization/concepts/#the-module-pattern:
// The module pattern
var feature = (function() {
// private variables and functions
var privateThing = "secret";
var publicThing = "not secret";
var changePrivateThing = function() {
privateThing = "super secret";
};
var sayPrivateThing = function() {
console.log( privateThing );
changePrivateThing();
};
// public API
return {
publicThing: publicThing,
sayPrivateThing: sayPrivateThing
};
})();
feature.publicThing; // "not secret"
// logs "secret" and changes the value of privateThing
feature.sayPrivateThing();
So using returning an object that aliases its "methods" could be another way to do it.
I've read from http://www.amazon.com/Programming-Oracle-Press-Poornachandra-Sarang-ebook/dp/B0079GI6CW that it is always good practice to use getters and setters rather that accessing the variable directly from outside the object, so that would eliminate the need of returning variables by reference.
BTW you could just use this.variable to reference/declare a public variable and var variable to declare a private variable.
I know this is a late answer, but I hope it helps anyone who reads it in the future.

Categories

Resources