nilgun
nilgun

Reputation: 10629

Accessing "name" of the subscribed variable in ko subscribe method

I know i can access the newValue of the subscribed variable but how can i access to the name of it:

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"
    });
}

Upvotes: 1

Views: 520

Answers (3)

Bertha
Bertha

Reputation: 29

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])

Upvotes: 0

vadim
vadim

Reputation: 1726

As solution you can assign class with needed properties instead of ko.observableArray();

For example you have class

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

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

And after that get car id within change function:

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

    });

}

Upvotes: 0

Engineer
Engineer

Reputation: 48813

Try like this:

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");
}

Upvotes: 3

Related Questions