JavaScript setTimeout in Object - javascript

I am trying to give an object a countdown timer and when the countdown is down it should call a function which removes this object from an array.
array = [];
var object = {
'name' : 'user',
'limit' : function() {
setTimeout(destroyMe(this),10000);
}
}
array.push(object);
var destroyMe = function(obj) {
array.remove(obj);
}
I know that there could a problem with the this but the timeout function doesnt work at all not even like this:
var object = {
'name' : 'user',
'limit' : function() {
setTimeout(console.log("dd"),3000);
}
}
Maybe someone can tell me the issue with my version of the setTimeout.
thx

setTimeout takes a reference to a function. The code you have is calling the function.
This should be changed to:
var object =
{
'name' : 'user',
'limit' : function()
{
setTimeout(function() { destroyMe(this); }, 10000);
}
}
(You may have issues using this in this context, try it!)
var object =
{
'name' : 'user',
'limit' : function()
{
setTimeout( function() { console.log("dd"); },3000);
}
}

You need to pass a function to setTimeout, not a function call.
var object = {
'name' : 'user',
'limit' : function() {
setTimeout(function() {
destroyMe(this)
}, 10000);
}
};
As you already know, the this probably doesn't do what you are expecting. Replacing destroyMe(this) with console.log("dd") should result in a behavior that you would expect.

setTimeout either takes a callback (a function, not a function call with arguments) or code in quotes. However, as noted in this question, passing a string is only allowed for historical reasons--there aren't any good reasons for doing it in practice.
But, for completeness sake, one way to do what you want is:
var object = {
'name' : 'user',
'limit' : function() {
setTimeout('console.log("dd")', 3000);
}
}

Related

Returning event listeners in javascript function

I'm wondering about what's happening when you end up doing something like this in a javascript function:
function() {
var privateMembers : {
'methodA' : function() {
},
'methodB' : function() {
}
};
var publicMembers = {
'methodC' : function() {
},
'methodD' : function() {
}
};
publicMembers.listen = {
"myEvent:Listener" : publicMembers.MethodC;
};
return publicMembers;
}
I understand that returning just publicMembers makes the methods available, however, I'm also wondering would that also make the publicMembers.listen available as well?
yes. these two codes are equivalent
var publicMembers = {
'methodC' : function() {
},
'methodD' : function() {
}
};
publicMembers.listen = {
"myEvent:Listener" : publicMembers.MethodC;
};
and:
var publicMembers = {
'methodC' : function() {
},
'methodD' : function() {
}
'publicMembers' : {
listen : {
"myEvent:Listener" : publicMembers.MethodC;
}
}
};
publicMembers.listen is just a property of publicMembers object, there is no difference between declaring properties using object literals or dot notation. So, when you add listen property to publicMembers object, and you return the whole object, surely you will have access to publicMembers.listen as well. It's pretty easy to test btw.

Passing variable into object method javascript

trying to get my head around objects, methods, closures, etc... in Javascript.
Can't see why this isn't working, some fundamental flaw in my thinking I guess. I'm expecting the val variable to be passed through to the addNote() function but it isn't. I thought that any variables declared outside of a function are available to that function, as long as they're not within another function. Is that not correct?
if(typeof(Storage) !== "undefined") {
console.log(localStorage);
var $input = $('#input'),
$submit = $('#submit'),
$list = $('#list'),
val = $input.val();
var noteApp = {
addNote : function(val) {
var item = val.wrap('<li />');
item.appendTo($list);
clearField();
},
clearField : function() {
$input.val = '';
},
delNote : function(note) {
}
};
$submit.on('click', function(){
noteApp.addNote();
});
} else {
}
I'm trying to learn how the pros manage to get their code so clean, concise and modular. I figured a note app would be a perfect start, shame I got stuck at the first hurdle...
Cheers.
There are several issues with the code in the question
defining an argument named val and not passing an argument to the function
when calling clearField() inside the object literal it's this.clearField()
You're only getting the value once, not on every click
val is a string, it has no wrap method
$input.val = ''; is not valid jQuery
I would clean it up like this
var noteApp = {
init: function() {
if (this.hasStorage) {
this.elements().events();
}
},
elements: function() {
this.input = $('#input');
this.submit = $('#submit');
this.list = $('#list');
return this;
},
events: function() {
var self = this;
this.submit.on('click', function(){
self.addNote();
});
},
hasStorage: (function() {
return typeof(Storage) !== "undefined";
})(),
addNote: function() {
this.list.append('<li>' + this.input.val() + '</li>');
this.clearField();
return this;
},
clearField: function() {
this.input.val('');
},
delNote : function(note) {
}
}
FIDDLE
Remember to call the init method
$(function() { noteApp.init(); });
In your call to addNote(), you don't pass any argument for the val, so it will be undefined:
noteApp.addNote();
// ^^ nothing
Pass the input (seems you want the jQuery object not the string value because of your val.wrap call):
noteApp.addNote($input);
When you declare the val in the function, it is scoped to that function and will only be populated if the function call passes a value for that argument. Even if you have another variable in an upper scope with the same name val, they are still differentiated. Any reference to val in the function will refer to the local val not the upper scope.

Unfamiliar syntax in javascript object

My question:
var nsPreferences = {
property1:"",
get mPrefService()
{
return Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
},
setBoolPref: function (aPrefName, aPrefValue)
{
try
{
this.mPrefService.setBoolPref(aPrefName, aPrefValue);
}
catch(e)
{
}
},
getBoolPref: function (aPrefName, aDefVal)// Prefs.jsで使用
{
try
{
return this.mPrefService.getBoolPref(aPrefName);
}
catch(e)
{
return aDefVal != undefined ? aDefVal : null;
}
return null; // quiet warnings
},
};
In this object nsPreferences, what is this "get mPrefService(){}"? This is the first time I've seen this kind of syntax in javascript object. Would anyone tell me about this syntax?
It's a getter function. It will look like a variable when you read it:
var someService = nsPreferences.mPrefService;
It calls that function without using the regular invocation parens. You can also use the set operator to create a "setter" function for the same property:
set mPrefService(val){
this.actualVal = val;
},
nsPreferences.mPrefService = "service";

Passing parameters between javascript asynchronous callback functions

I want to use the execAsync function here:
https://developer.mozilla.org/en/Storage#Asynchronously
and I want to pass values between handleResult and handleCompletion. Something like
statement.executeAsync({
handleResult: function(aResultSet) {
VALUE = 1
},
handleCompletion: function(aReason) {
print(VALUE);
}
});
What's the best way to do it?
var value;
statement.executeAsync({
handleResult : function(aResultSet) {
value = 1;
},
handleCompletion : function(aReason) {
print(value);
}
});
Well the obvious thing to notice is that you're passing an object to executeAsync. (In particular, it's a mozIStorageStatementCallback, so it should have a handleError method too.) So you can easily associate properties specific to that object with the object, using the "this" keyword:
statement.executeAsync({
value: 1,
handleResult: function(aResultSet) {
this.value = 0;
},
handleError: function(aError) {
this.value = 2;
},
handleCompletion: function(aReason) {
print(this.value);
}
});

how is the dom cached between functions in an object literal? (Javascript)

Ok I'm not sure the title of this post is the correct way to refer to what I mean and I'm pretty sure I already know the answer to this question but I just wanted some clarification.
If I have an oject like this
var myObj = {
settings : {
domObj = document.getElementById('elem1');
},
myFunc1 : function () {
return this.domObj;
},
myFunc2 : function () {
return this.domObj;
}
}
myObj.myFunc1();
myObj.myFunc2();
Is the domObj cached the first time it is accessed or is the dom traversed in both functions? I am attempting to access the Dom only once but not sure if this is a possible solution.
Assuming you really meant this:
var myObj = {
settings : function() {
domObj = document.getElementById('elem1');
},
myFunc1 : function() {
return this.domObj;
},
myFunc2 : function() {
return this.domObj;
}
};
the answer is that "domObj" is a global variable because you forgot the var keyword. Now, you may have meant this:
var myObj = {
domObj: null,
settings : function() {
this.domObj = document.getElementById('elem1');
},
myFunc1 : function() {
return this.domObj;
},
myFunc2 : function() {
return this.domObj;
}
};
in which case "domObj" is just a property of "myObj". It'd get set if you call
myObj.settings();
Assuming your doing "this.domObj =" and the other corrections you've noted; yes; the DOM element is cached in this.domObj. The only time the DOM is actually traversed is when you're calling DOM traversal methods. Assigning a DOM element to a variable/object property works exactly the same as any other assignment.

Categories