2017-08-31 20 views
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); 

回答

1

從敲除docs

的訂閱功能接受三個參數:回調是稱爲每當通知發生的功能,目標(可選)定義在回調函數的這個值,事件(可選;默認爲「更改」)是要接收通知的事件的名稱。

所以,如果你提供的視圖模型作爲第二個參數「目標」,以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> 
相關問題