Reputation: 10629
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
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
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
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