简体   繁体   English

node.js如何向字符串添加onchange事件

[英]nodejs how to add onchange event to a string

Is it possible to add an onchange event to a string ? 是否可以向字符串添加onchange事件?

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. 不,这是不可能的,因为字符串在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 因此,即使您以某种方式将事件附加到String.prototype ,也无法检测到更改,因为字符串永远都不会更改

Because of the answer of "macek" (thanks by the way) this is not a right answer, but a "workaround" thats works good for me. 由于回答“ macek”(顺便说一句),这不是一个正确的答案,但是“解决方法”对我来说很有效。 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM