I have simple example:
function File(name) {
this.name = name
this.text = null
}
File.prototype = {
read: function() {
fs.readFile(this.name, function (err, data) {
}
},
getContent: function() {
return this.text
}
}
var myfile = new File('my_file')
watch.createMonitor('my_file_dir', function (monitor) {
monitor.files['my_file']
monitor.on("change", function (f, stat) {
myfile.read()
}
})
main program....:
myfile.getContent() ...
I want to add file contents in this.text variable. How to do it ?
Create local variable and store there ‘this’
read: function() {
var _file = this;
fs.readFile(this.name, function (err, data) {
…
_file.text = data;
…
});
},
Bind ‘this’ to inner function:
read: function() {
},
Note:
It’s insufficiently to store data to this.text: if you read something asynchronously in yur class, you need to provide callbacks to let other objects know that you got some data in yourFile.text