I've been messing around with using Node.js and CouchDB. What I want to be able to do is make a db call within an object. Here is the scenario that I am looking at right now:
var foo = new function(){
this.bar = null;
var bar;
calltoDb( ... , function(){
// what i want to do:
// this.bar = dbResponse.bar;
bar = dbResponse.bar;
});
this.bar = bar;
}
The issue with all of this is that the CouchDB callback is asynchronous, and "this.bar" is now within the scope of the callback function, not the class. Does anyone have any ideas for accomplishing what I want to? I would prefer not to have a handler object that has to make the db calls for the objects, but right now I am really stumped with the issue of it being asynchronous.
To listen to class change we need to instantiate the MutationObserver object, pass the callback function, and call the observe() method. The observe() method accepts two arguments the target node and options object which should contain attributes property that is set to true.
To set up an event listener you just need to have a variable that references an element and then call the addEventListener function on that element. This function takes a minimum of two parameters. The first parameter is just a string which is the name of the event to listen to.
$ is simply a valid JavaScript identifier. JavaScript allows upper and lower letters, numbers, and $ and _ . The $ was intended to be used for machine-generated variables (such as $0001 ). Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).
Just keep a reference to the this
around:
function Foo() {
var that = this; // get a reference to the current 'this'
this.bar = null;
calltoDb( ... , function(){
that.bar = dbResponse.bar;
// closure ftw, 'that' still points to the old 'this'
// even though the function gets called in a different context than 'Foo'
// 'that' is still in the scope and can therefore be used
});
};
// this is the correct way to use the new keyword
var myFoo = new Foo(); // create a new instance of 'Foo' and bind it to 'myFoo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With