我有以下 JavaScript 数据模型:
function User(uid, usr_name, usr_pwd, usr_enbld) {
var id = uid == null ? uuid.v4() : uid;
var name = usr_name;
var password = usr_pwd;
var enabled = usr_enbld;
Object.defineProperty(this, "id", {
get: function () {
return id;
}
});
Object.defineProperty(this, "name", {
get: function () {
return name;
},
set: function (value) {
name = value;
}
});
Object.defineProperty(this, "password", {
get: function () {
return password;
},
set: function (value) {
password = value;
}
});
Object.defineProperty(this, "enabled", {
get: function () {
return enabled;
},
set: function (value) {
if (!value instanceof Boolean) {
// log - type error, must be true/false
return;
}
enabled = value;
}
});
}
我试图找出当其中一个属性发生更改时如何引发事件。我为nodejs找到的观察者库似乎都非常困难。也许我没有正确实现它,但我认为我可以在“propertyChanged”事件上使用bind和
trigger`。但这没有用。
最佳答案
我认为 ECMAScript 中尚未包含此功能,但稍后他们将提供类似 Object.observe 的内容,它将对象绑定(bind)到一个函数。
如果您使用的是 chrome 36
或更高版本,您应该能够在控制台中使用它。
// Let's say we have a model with data
var model = {};
// Which we then observe
Object.observe(model, function(changes){
// This asynchronous callback runs
changes.forEach(function(change) {
// Letting us know what changed
console.log('Printing Changes.');
console.log(change.type, change.name, change.oldValue);
});
});
现在,如果您要添加、删除或修改模型的属性,它将调用该函数。
您可能想查看watch ,但是如果你看看 MDN,他们说不建议使用这个。
注意:-如果你想将Observe
与node
一起使用,它在当前稳定版本的nodejs中不可用,但你可以使用 Node v0.11.* 支持此功能。
如果您使用的是node v0.11
,请确保运行您的程序
node --harmony filename.js
关于javascript - 如何引发属性(property)变更事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27996033/