How to use javascript namespaces? - javascript

I am trying to figure out JavaScript namespaces... I would like to write couple of functions and secure them in namespaces like below.. but I think I don't get it very well..This is too simple question but it will be clear for me I guess If I see why that doesn't work..
Here an exp that I am trying:
var myApp = {
getTxt: function(x){
x.click(function(){
var txt = $(this).html();
alert(txt);
});
};
};
call myApp:
var box = $('.js-box');
alert(myApp.getTxt(box));
I think MyApp is created rightly but I am not sure about calling and firing the getTxt function..
Calling that:
myApp.getTxt(box)
doesn't mean to fire x.click function..? Why does it turn an object?
What am I doing wrong here? Thanx!
http://jsfiddle.net/67b02cht/1/

You are defining myApp as an object, So here is a problem, You are giving ; after defining the field, which you can't. It'll cause a syntax error.
var myApp = {
getTxt: function(x){
x.click(function(){
var txt = $(this).html();
alert(txt);
});
} //<<<<-------------here was a semicolon,
};
And you are calling the function like bellow in alert it will cause an undefined alert because you are not returning anything from the function. Just call
myApp.getTxt(box)
And it will show the content on click.
DEMO

How about a modular approach.
var MyApp = MyApp || {};
MyApp.Module = (function () {
function App() {
}
App.prototype.getTxt = function(x){
//your code here
}
return App;
})();
Use it this way:
var box = $('.js-box');
alert(new MyApp.Module.getTxt(box));

Related

Javascript function undefined return

<script>
var tarih = tarih();
alert(tarih);
function tarih() {
var s=emrah;
return(s);
}
</script>
Bu fonksion neden undefined dönüyor ?
Why "undefined" returns?
The reason it returns undefined, is because of the assigment
var s = emrah
is confusing JS. So, it looks for a var name emrah and doesn't find it. That is the reason, you get undefined. Plus, if you are looking at your console, it would already have given you an error message, that
emrah is not defined
You might want to try: (If that's what you wanted)
var s = 'emrah'
You are calling the method before its defined.
Change the code to something like this.
<script>
function tarih() {
var s='emrah';
return(s);
}
var tarih = tarih();
alert(tarih);
</script>

Error undefined is not a function for .click()

I keep getting undefined is not a function error and I don't know why, can anyone help shed some light.
here is the whole bit of code
(function(){
var sliders = $('section.content-25').hide();
var slidersOrder = sliders.each(function(i){
var i = i - 1;
$(this).addClass("slider"+(i+1));
});
$(".project-wrapper").on('click', function(){
var btnOrder = $(this).index();
var sliderClass = ("slider"+btnOrder);
if (sliders.hasClass("slider"+btnOrder)) {
sliderClass.show();
};
event.preventDefault();
});//end of .on('click') function
})();// end self envoking functions
EDIT2: jsfiddle.net/Grimbode/LpuLE/4
EDIT: Tried making sense from your code. Here is a working example. http://jsfiddle.net/Grimbode/LpuLE/3/
You had a couple problems with your code. I fixed most of them. You only need to make sure that this part : var sliderClass = ("slider"+btnOrder); is what you actually meant to do. To me it looks wrong. Looks as if you're trying to access an element and that it should look like: var sliderClass = $("#slider "+btnOrder); or something like that.
$('#slider1').hide();
$(".project-wrapper").on('click', function(){
var btnOrder = $(this).index();
alert(btnOrder);
var sliderClass = $("#slider"+btnOrder);
if (sliderClass.hasClass("slider"+btnOrder)) {
sliderClass.show();
}
});
You are using an undefined variable in your code -
if (sliders.hasClass("slider"+btnOrder)) {
sliders is not defined in the function anywhere.
Your js has lots of problem I think:
where sliders variable is defined??
var sliderClass // I think you are trying to create jQuery DOM object here which is not correct
It should be something like this
var sliderClass = $(".slider"+btnOrder);

Separate Code javascript without using jquery ($ symbol) knockout.js

Good. I want to separate my code without using Jquery lib(symbol $).
I am trying this method:
This is my App.js
var window.myGlobalVariable = {};
(function(namespace){
(function App(){
var app1 = myGlobalVariable.app1 ;
});
namespace.App = App;
})(window.myGlobalVariable);
this is my app1.js
(function(namespace){
(function app1 (namespace){
//do something example : console.log("hello world")
});
namespace.app1 = app1 ;
})(window.myGlobalVariable);
but it does not work....
(error: app1 is undefined)
I must create a Webpage with lib knockout.js but i cannot use
jquery
some suggestions?
You make a slight mistake with the initialization of the "namespace" variable.
This will work:
// Note that I've removed 'var'
window.myGlobalVariable = {};
(function(namspace){
function App(){
var app1 = myGlobalVariable.app1 ;
};
namespace.App = App;
})(window.myGlobalVariable);
In reality you will probably have several of these scoped things in you application. In that case, I think this is better:
(function(namspace){
namespace.App = function(){
// Do what you need to do.
};
})(window.myGlobalVariable = window.myGlobalVariable || {});
The expression window.myGlobalVariable = window.myGlobalVariable || {} uses the instace if present otherwise initializes it. This way, the order of your modules make no difference at all.

Create a string (text) that declares variable and its value, for use in Javascript

I am messing with Javascript code that needs to have variable dynamic part.
I am trying to substitute this piece of Javascript code:
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
with something like:
var encapsulatedData = "var data = document.getElementById('IDofSomeHiddenField').value;";
var encapsulatedPrint = "var print = document.getElementById('IDofOutputField');";
so that when I use somewhere in Javascript code:
encapsulatedData;
encapsulatedPrint;
this will work:
print.value = data;
But it does not work.
Is there a way how to declare:
var encapsulatedData
var encapsulatedPrint
in similar manner like I wrote above, so that:
print.value = data;
works?
Do you mean magically create global variables?
function encapsulatedData() {
window.data = document.getElementById('IDofSomeHiddenField').value;
}
function encapsulatedPrint() {
window.print = document.getElementById('IDofOutputField');
}
encapsulatedData();
encapsulatedPrint();
print.value = data;
This is not very sanitary code, and what you want is probably not what you should be doing. Could you step back and say what your goal is, rather than the means to that goal? I suspect what you really want to be using are closures or returning first-class functions for delayed evaluation.
For example:
function makePrinter(id) {
var outputfield = document.getElementById(id);
return function(value) {
outputfield.value = value;
}
}
function getValue(id) {
return document.getElementById('IDofSomeHiddenField').value;
}
var data = getValue('IDofOutputField');
var print = makePrinter('IDofOutputField');
print(data);
You have a syntax error I think. You're not closing the parentheses on the first and second lines.
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
It is also bad form to use JS evaluation like you're attempting to do. If anything you really want to create a function for each of the page elements that returns the page element. ECMAScript 5 has properties which I think is sort of what you're looking for with what you're trying to do but that isn't how ECMAScript 3 JS can work.

JavaScript object is undefined

I need some help please with a javascript object. it goes like this:
I call this function addFilter(element) with a html DOM element.
The function looks like this:
function MyList() {
this.arr = new Array();
this.index = 0;
}
MyList.prototype.add = function(filter) {
this.arr[this.index++] = filter;
//alert(this.arr[0] + ' mylist arr');
}
function Filter(element) {
this.setElement(element);
}
Filter.prototype.setElement = function (element) {
this.element = element;
this.kinorid = $(element).attr('id');
}
function addFilter(element) {
filters.Add(new Filter(element));
}
var filters = new MyList();
Now with in another function that in my case the function creates the jquery UI Slider, and every time the slider changes i need to get the parent element of that element that was sent to addFilter like i said in the beginning. so then i try doing
var value = filters.arr[0];
but like i said it id undefined.
Can any one please help me by reviewing the code, and tell me whats wrong.
Thank you very much.
You still haven't said where or how you're using filters.arr[0], without which it's very difficult to help you.
Assuming your code using it looks something like this:
AddFilter($("#theElement"));
display(typeof filters.arr[0]);
filters.arr[0].element.css("color", "blue");
It should be working; live example.
My only thought is if AddFilter and filters are not defined within the same scope. You're using filters within AddFilter, so AddFilter must be defined in the same scope as filters (or in a sub-scope). So this would be fine:
var filters;
function AddFilter() { ... }
And this
function AddFilter() { ... }
var filters;
And this
var filters;
$(function() {
function AddFilter() { ... }
});
But not
function AddFilter() { ... }
$(function() {
var filters;
// ...
});
...because in that last case, AddFilter is defined outside the scope in which filters is defined.
Your code is very convoluted, I don't understand it at all. Anyway, you are looking for (I think):
var value = filters.arr[0].element;
since you assign the element reference to arr[this.index].
Incidentally, if you are passing an element, then:
$(this).attr('id');
is an awfully slow way to do:
this.id;
Edit
The code I used (where there was a div with id 'd0' in the DOM):
var filters = new MyList();
AddFilter(document.getElementById('d0'));
alert(filters.arr[0].element);

Categories