Is it possible to add an onchange event to a string ?
I want something like this:
var myString = '';
var doSomething = function(){
console.log('string changed');
};
myString.on('change',doSomething);
myString = 'new'; //at this point the on('change') event should be run
No, this is not possible as strings are immutable in JavaScript.
Any string operation that appears as though it's changing a string is actually creating a new string.
So, even if you were to somehow attach events to String.prototype
, there's no way to detect a change since a string can never change
Because of the answer of "macek" (thanks by the way) this is not a right answer, but a "workaround" thats works good for me. Maybe someone else helps this too.
var events = require('events');
var myString = function(val){
this.myVal = val;
this.change = function(newVal)
{
if(newVal !== this.myVal){
this.myVal = newVal;
this.emit('changed');
}
}
this.val = function(){
return this.myVal;
}
};
myString.prototype.__proto__ = events.EventEmitter.prototype;
var doSomething = function(){
console.log('string changed');
};
var somestring = new myString('');
console.log(somestring.val()); // output ''
somestring.on('changed',doSomething);
somestring.change('new'); //output doSomething() -> 'string changed'
console.log(somestring.val()); //output 'new'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.