1

我知道我可以访问订阅变量的 newValue 但我如何访问它的名称:

for ( var i = 0; i < carSelects.length; i++) {
    var carId = $(carSelects[i]).attr('carId');
    self["cars_" + carId + "_selected"] = ko.observableArray();
    self["cars_" + carId + "_selected"].subscribe(function(newValue) {
       // here i want to access the name of the subsribed variable 
       // i.e. "cars_" + carId + "_selected"
    });
}
4

3 回答 3

3

试试这样:

for ( var i = 0; i < carSelects.length; i++) {
   var carId = $(carSelects[i]).attr('carId');
   (function(name){
       self[name] = ko.observableArray();
       self[name].subscribe(function(newValue) {
           alert(name);
       });
   })("cars_" + carId + "_selected");
}
于 2012-07-24T06:51:56.060 回答
0

This is a hack, but you can obtain the name of the subscribed variable via the event.srcElement and get the value of the element's "data-bind" attribute, like below:

var id= $.trim(event.srcElement.attributes["data-bind"].value.split(':')[1])
于 2015-01-22T23:26:55.213 回答
0

作为解决方案,您可以分配具有所需属性的类而不是 ko.observableArray();

例如你有课

function CarClass(carId, changeCallback) {
   this.carId = carId;
   this.array = ko.observableArray();
   var self = this;

   self.array..subscribe(function(newValue) { 
      changeCallback(self.carId, newValue);
   });
}

然后在更改功能中获取汽车ID:

for ( var i = 0; i < carSelects.length; i++) {
    var carId = $(carSelects[i]).attr('carId');
    self["cars_" + carId + "_selected"] = new CarClass(carId, function(carId, newValue) {

    });

}
于 2012-07-24T06:59:15.570 回答