Which is the best way between:
var myClass = function() {
this.myContainer = function(){ return $(".container");}
this.mySubContainer = function(){ return this.myContainer().find(".sub"); }
}
AND
var myClass = function() {
this.myContainer = $(".container");
this.mySubContainer = this.myContainer.find(".sub");
}
Is there any concrete differences?
The memory problem arose when I have seen that my web page, that has enough javascript ( about 150KB of mine + libs ) takes more then 300-400MB of RAM. I'm trying to find out the problem and I don't know if this could be one of them.
function myClass{
this.myContainer = function(){ return $(".container");}
this.mySubContainer = function(){ return this.myContainer().find(".sub"); }
}
Here you will need to call it something like myClassInstance.myContainer() and that means jquery will search for .container element(s) any time you are using that function. Plus, it will create 2 additional closures any time you will create new instance of your class. And that will take some additional memory.
function myClass{
this.myContainer = $(".container");
this.mySubContainer = this.myContainer.find(".sub");
}
Here you will have myContainer pointing to an object which already contains all links to DOM nodes. jQuery will not search DOM any time you use myClassInstance.myContainer
So, second approach is better if you do not want to slow down your app. But first approach could be usefull if your DOM is frequently modified. But I do not beleave you have it modified so frequently that you may need to use second approach.
If there is a single variable you are trying to assign , then the second approach looks cleaner..
Yes they are different.
MODEL 1:
In the first model, myContainer is a function variable.It does not contain the jQuery object.You cannot call any of jQuery's methods on the objet. To actually get the jQuery object you will have to say
var obj = this.myContainer() or this.myContainer.call()
MODEL 2:
The second model stores the actual jQuery object.
try alerting this.myContainer in both models, u will seee the difference.
Yes this is different. after you fix your syntax error :
function myClass(){... // the parentheses
1st
When you create a new object var obj = new myClass(), you are creating two functions, and the jquery object is not returned until you call it
var container = obj.myContainer();
2nd
As soon as the object is initialized the dom is accessed and you have your objects cached for later use;
var container = obj.myContainer;
Related
Working with multiple closures has me all turned around. It seems that you define a variable in one closure then return it publicly so it can be accessed. Returning it requires giving it a public name. Then you pull it into another closure by defining it as a new variable with yet a third name?
My head is spinning a bit.
Here's a code snippet. It obviously doesn't work (obvious to you maybe, I had to struggle to get this far) Where am I breaking down? AM I making this too difficult on myself? Is there a simpler way or merely a 'best practice' way?
If this is the correct course... I'll commit to it. I'm not looking for an easy answer, but I am looking to truly grasp what I'm doing rather than regurgitate structures I've seen somewhere already. Thanks in advance.
//CREATES A PRIVATE CLOSURE TO GRAB DOM CLASS & ASSOCIATED VALUE
var createUI = (function(){
//Stores a class from DOM into VARIABLE
var buttonClass = ".add__btn";
//RETURNS...
return {
// THE VALUE FOUND IN THE DOM ELEMENT OF THE STORED CLASS ABOVE
classPublicValue : function(){
return {
value: document.querySelector(buttonClass).value
}
},
// RETURNS THE CLASS ITSELF FOR FUTURE SHORTHAND USAGE. A GOOD PRACTICE I'M TOLD??
theClass : function() {
return buttonClass;
}
}
})();
//CREATES A SECOND PRIVATE CLOSURE TO PERFORM ACTION ON CLICK THAT USING STRUCTURES FROM FIRST CLOSURE.
var clickToHappen = (function() {
//PULLS IN THE CLASS ".add__Btn" as a string.
var myClass = createUI.theClass();
//POINTS TO THE VALUE OF THE ELEMENT CONTAINING THE PULLED IN CLASS.
var myValue = createUI.classPublicValue();
//RETURNS...
return{
clickMe : function(){
//A CLICK LISTENER ON DOM ELEMENT WITH CLASS CHOSEN IN FIRST PRIVATE CLOSURE.
document.querySelector(myClass).addEventListener('click', function() {
//STORES CURRENT VALUE INTO VARIABLE
var value = createUI.classPublicValue();
//PRINTS THAT VALUE TO CONSOLE
console.log(value);
});
}
}
})();
I created a namespace to hold variables so that 2 different functions could use them. My first variable uses jQuery and works fine. The second tries to use the variable established in the previous line and fails. It's undefined.
example:
varHolder = {
buildStep4: $('#buildStep4'),
jetSpan: buildStep4.find('#jetSpan')
};
Is there a way to do this properly?
You can capture the value, but use a function to keep it scoped so it doesn't exist after you've created your object.
varHolder = (function() {
var buildStep4 = $('#buildStep4');
return {
buildStep4: buildStep4,
jetSpan: buildStep4.find('#jetSpan')
}
})();
You could also build your object piecemeal:
varHolder = {};
varHolder.buildStep4 = $('#buildStep4');
varHolder.jetSpan = varHolder.buildStep4.find('#jetSpan');
Ids can't be duplicated inside a valid HTML document so it make no sense to provide context to an id selector, you can simply do
jetSpan: $('#jetSpan')
Been trying to instantiate an object (called "isSize" below) and assign it to another existing variable (called "sizeObject"), here is the first object ("isSize") within a function:
function Size(isSize) {
this.isSize = 80;
setSize(this.isSize);
}
And here's the second variable of which I want to assign the previous variable to:
var sizeObject;
I've been trying various ways such as the following:
function createSize(isSize){
var isSize = new sizeObject();
}
Anyone got any ideas? Many thanks
If I understand your comment correctly, here is what you are looking for:
// this is the constructor of the `Size` class
function Size() {
this.isSize = 80;
}
function createSize() {
// add this line:
var sizeObject = new Size();
}
It's very hard to understand quite what you're asking, but this:
var sizeObject = new Size(20);
...will create a new object with a isSize property on it with the value 20 if you change Size to:
function Size(initialSize) {
this.isSize = initialSize;
}
(E.g., so it actually uses the argument you give it, rather than using an hardcoded 80.)
Size in the above is a constructor function. You use constructor functions via new.
I'm looking for patterns which have been found acceptable when working with instances of js objects on the same page. (If there is a thread already covering this, a link will be appreciated.)
The issue is one of reference. After an object/feature is instantiated, it has to be referenced at some point later.
I've seen jQuery people store a reference to the object on the target DOM element using data(). However, I'm interested in a framework agnostic option if possible.
This could be accomplished if there was a clean, viable way to generate an unique id for a DOM element. Alas, I have not found one yet.
So my question is: What is the best way to store reference to an object, via a DOM element, so that you can reference it at a future arbitrary time?
Hopefully this makes sense, and I'm not just rambling. :)
Thanks.
There is nothing stopping you from maintaining your own cache:
var cache = [];
function locate(el) {
// search for the element within our cache.
for (var i=0;i<cache.length;i++) {
if (cache[i].elem === el) {
return cache[i].data;
};
};
// if we get this far, it isn't in the cache: add it and return it.
return cache[cache.push({
elem: el,
data: {}
}) - 1].data;
};
// used to add data to an element and store it in our cache.
function storeData(el, data) {
var store = locate(el);
for (var x in data) {
store[x] = data[x];
};
};
// used to retrieve all data stored about the target element.
function getData(el) {
return locate(el);
};
and then use as follows:
storeData(document.getElementById("foo"), {
something: 4,
else: "bar"
});
var data = getData(document.getElementById("foo"));
alert(data.something); // "4";
Objects in JavaScript (unlike classical OOP languages) can be augmented. There's nothing wrong with that; that's the way JavaScript was designed to be used:
Write:
document.getElementById( 'foo' ).customAttribute = 5;
Read:
alert( document.getElementById( 'foo' ).customAttribute );
If you don't want to alter the original object, the only way to point at it is using a dictionary as pointed out in one of the previous answers; however, you don't need to do a linear search to find the object: it can be done in logarithmic time providing you use an ID per element (potentially not its HTML ID but a custom one)
I have a function that takes a string object name and I need the function to create an new instance of a object that has the same name as the value of the string
For example,
function Foo(){}
function create(name){
return new name();
}
create('Foo'); //should be equivalent to new Foo();
While I know this would be possible via eval, it would be good to try and avoid using it. I am also interested if anyone has an alternative ideas to the problem (below)
I have a database and a set of (using classical OO methodology) classes, roughly one for each table that define common operations on that table. (Very similar to Zend_Db for those who use PHP). As everything is asynchronous doing tasks based on the result of the last one can lead to very indented code
var table1 = new Table1Db();
table1.doFoo({
success:function(){
var table2 = new Table2Db();
table2.doBar({
notFound:function(){
doStuff();
}
});
}
});
The obvious solution is to create helper methods that abstracts the asynchronous nature of the code.
Db.using(db) //the database object
.require('Table1', 'doFoo', 'success') //table name, function, excpected callback
.require('Table2', 'doBar', 'notFound')
.then(doStuff);
Which simplifies things. However the problem is that I need to be able to create the table classes, the names of which can be inferred from the first augment passed to require which leads me to the problem above...
Why not simply pass the constructor function into the require method? That way you sidestep the whole issue of converting from name to function. Your example would then look like:
Db.using(db) //the database object
.require(Table1Db, 'doFoo', 'success') //table constructor, function name, expected callback
.require(Table2Db, 'doBar', 'notFound')
.then(doStuff);
However, if you really want to use a string...
Why are you deadset on avoiding using eval? It is a tool in the language and every tool has its purpose (just as every tool can be misused). If you're concerned about allowing arbitrary execution, a simple regular expression test should render your usage safe.
If you're dead-set on avoiding eval and if all of your constructor functions are created in the default global scope (i.e. the window object), this would work:
function create(name) {
return new window[name]();
}
If you want to get fancy and support namespace objects (i.e. create('MyCompany.MyLibrary.MyObject'), you could do something like this:
function create(name) {
var current,
parts,
constructorName;
parts = name.split('.');
constructorName = parts[parts.length - 1];
current = window;
for (var i = 0; i < parts.length - 1; i++) {
current = current[parts[i]];
}
return new current[constructorName]();
}
You were at the gate of completeness. While Annabelle's solution let's you to do what's you've just wanted in the way you wanted (passing strings), let me offer you an alternative. (passing function references)
function Foo(){}
function create(name){
return new name();
}
create(Foo); // IS equivalent to new Foo();
And voila, it works :) I told you. You were at the doorsteps of the solution.
What happened is that you've try to do this
new 'Foo'()
Which doesn't makes much sense, does it? But now you pass the function by reference so the line return new name(); will be transformed into return new Foo(); just how you would expect.
And now the doors are opened to abstract the asynchronousness of your application. Have fun!
Appendix: Functions are first-class objects, which means that they can be stored by reference, passed as an argument by reference or returned by another function as values.