4

当我们将一个函数订阅多个属性时,有什么方法可以找到哪个属性正在调用订阅的函数?

代码示例。

var self = this;
$(document).ready(function(){

var myViewModel = 
{
    FirstName : ko.observable("Bert"),
    LastName : ko.observable("pual")
};
myViewModel.FirstName.subscribe(self.notifyChange);

myViewModel.LastName.subscribe(self.notifyChange);

ko.applyBindings(myViewModel);
});
notifyChange = function ( newValue ) {// want to find which property(FirstName/LastName) is calling the function }

HTML

<body>
Enter your name:
<input id="source" data-bind="value: FirstName" />
<input id="Text1" data-bind="value: LastName" />    

在这里,我为 FirstName 和 LastName 订阅了“notifyChange”功能。如果任何一个值发生更改,它将调用 notifyChange 函数,我想知道哪些属性更改会调用 notifyChange 函数?

4

2 回答 2

2

You can't tell who actually called the function.

One choice would be to use your notifyChange function, but bind it in each case to the appropriate property. Now, this will be set to either the FirstName or LastName observable. Doing a bind does create a wrapper to the function, but at least your actual implementation in notifyChange will only exist once.

myViewModel.FirstName.subscribe(self.notifyChange.bind(myViewModel.FirstName));
myViewModel.LastName.subscribe(self.notifyChange.bind(myViewModel.LastName));

So, this inside of notifyChange will be the appropriate observable.

于 2012-05-17T15:38:11.313 回答
0

我意识到这个问题是在 6 年前提出并回答的。但也许我的回答对某人仍然有用。

接受的答案基于将 observable 作为回调函数的上下文传递。顺便说一句,您不必使用bind(),您可以将上下文作为第二个参数传递给subscribe()

myViewModel.FirstName.subscribe(self.notifyChange, myViewModel.FirstName);

淘汰赛在bind()内部使用。

但是,如果你(像我一样)不能改变你的回调函数中的上下文(我需要那个上下文中的属性和函数),为什么不简单地将你的回调函数包装在另一个函数中并将一个额外的参数传递给回调功能:

myViewModel.FirstName.subscribe(function (value) { self.notifyChange('FirstName', value); });
myViewModel.LastName.subscribe(function (value) { self.notifyChange('LastName', value); });

如果你在一个循环中使用它,假设你正在枚举你的 ViewModel 的属性,你可以像这样将整个东西包装在一个 IIFE 中:

// .. property is an enumerated reference to an ko.observer
// .. propertyName is a string identifying it (for instance 'FirstName')
(function (elementName) {
    property.subscribe(function(value) { 
        self.notifyChange(elementName, value);
    });
})(propertyName);
于 2018-06-26T18:24:55.513 回答