i来自C#环境,我们有InotifyPropertyChanged接口。当订阅此属性更改事件时,将接收发件人和属性名称。在此示例中,发件人是ViewModel。我想与淘汰赛有类似的东西。我试图将函数的实例订阅并存储到包含带有ViewModel和PropertyName参数的对象的标签上。因为可观察到的新值不足以使我想使用该事件。
如何使用与C#的InotifyPropertychanged相似的KO创建代码?
这是我写的一些废话,以表明我已经付出了一些努力。但是我在这里失败了。
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);
来自淘汰文档:
订阅函数接受三个参数:回调是每当通知发生时,target(可选)在回调函数中定义此值的函数,事件(可选;默认为"更改")是名称接收通知的活动。
因此,如果将ViewModel作为第二个参数"目标"提供给subscribe()
,则可以在处理程序中以this
访问它。例如:
<p data-bind="text: counter"></p>
<button data-bind="click: buttonClicked">Increment</button>
<script type="text/javascript">
var ViewModel = function() {
this.counter = ko.observable(0);
this.buttonClicked = function() {
this.counter(this.counter() + 1);
};
this.counter.subscribe(function(newValue) {
console.log(newValue);
console.log(this);
}, this);
};
ko.applyBindings(new ViewModel());
</script>