0
我來自C#環境,那裏有INotifyPropertyChanged接口。當訂閱此屬性更改事件時,會收到發件人和屬性名稱。在這個例子中發件人是ViewModel。我想和KnockoutJS有類似之處。我嘗試訂閱並將函數的實例存儲到包含具有ViewModel和PropertyName參數的對象的散列表中。因爲可觀察值中的新值不足以滿足我想要使用該事件的需求。如何將全局屬性更改爲KnockoutJS事件處理程序
如何使用與C#的INotifyPropertyChanged類似的方式創建代碼?
這是我寫給你看的一些廢話,我已經付出了一些努力。但我在這裏失敗悲慘。
var propertyChangedHashTable = new Hashtable();
function PropertyChanged(newValue) {
console.log(this);
var changedEventParams = propertyChangedHashTable[this];
console.log(changedEventParams);
//gateway.propertyChanged(changedEventParams.viewModel, changedEventParams.propertyName, newValue);
};
function subscribePropertyChanged(viewModel, objectPath) {
if (typeof objectPath === "undefined" || objectPath == null) objectPath = "";
if (objectPath.length !== 0) objectPath += '.';
var observable = ko.observable("").toString();
for (var propertyName in viewModel) {
var viewModelName = viewModel.__proto__.constructor.name;
var localObjectPath = objectPath + viewModelName;
var property = viewModel[propertyName];
if (propertyName.indexOf("ViewModel") !== -1) {
subscribePropertyChanged(property, localObjectPath);
continue;
}
var isObservable = property.toString() === observable.toString();
if (!isObservable) continue;
var propertyChangedFunc = PropertyChanged;
propertyChangedHashTable.put(propertyChangedFunc, 'test');
property.subscribe(propertyChangedFunc);
}
}
function MainViewModel() {
var self = this;
self.isRecording = ko.observable(false);
self.dataDirectory = ko.observable("C:\\Temp\\Recordings");
self.toggleIsRecording = function() {
self.isRecording(!self.isRecording());
};
}
var viewModel = new MainViewModel();
subscribePropertyChanged(viewModel);