Yuriy
Yuriy

Reputation: 83

Add item to Observable Array Knockout

I have 3 Observable Arrays:

self.sets1 = ko.observableArray([
    ]);
self.sets2 = ko.observableArray([
    ]);
self.sets3 = ko.observableArray([
    ]);

I have a constructor to make new records.

function Record(name1){
    var self = this;
    self.name = ko.observable(name1);
    this.editing = ko.observable(false);
    this.edit = function() { this.editing(true) }
    self.remove = function(){
        self.remove(this);
    }

}

I have a function that adds records to one of my observable arrays. Like so:

this.addSet = function(){
        self.sets1.push(new Record($('input[id=weight1]').val()+' x '+$('input[id=reps1]').val()));
    };

And in my view I call it like this:

<button id="btn1" data-bind="click: addSet">Add set</button>

But this is only for observable array sets1.

What I want is to make this function universal, so it could add records to any array, for example depending of the id of the button which is clicked. But how can I get the needed id and pass this value to my function? Or maybe there's a better solution?

Thanks.

Upvotes: 1

Views: 248

Answers (1)

Nathan
Nathan

Reputation: 1705

Knockout event bindings (like click) are provided two parameters that you may find useful.

function(data, event)

Here, data is the knockout object associated with the element that raised the event. event is the event object which contains data about the event. event.target is a reference to the html element that raised the event.

So to find the ID of the button that was clicked, do something like this:

this.addSet = function(record, event){
    var id = $(event.target).attr('id');
    ...
};

Upvotes: 1

Related Questions