DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

Removing property inside observable array

If i define object like

var Person = function(id, name, country) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.country = ko.observable(country); 

    return self;
};

How can i remove property "country" from this object on click event of button. Thing is that when i send data to webservice i dont want to send this property to it.

Please see fiddle here where i am trying to remove property "country" on click event of save button. http://jsfiddle.net/kirannandedkar/nZDrk/7/

Upvotes: 1

Views: 827

Answers (3)

Jeff Mercado
Jeff Mercado

Reputation: 134881

Since you're sending the data to this webservice, what you should be doing is implementing the toJSON() function on your object and remove the property there. Then send the result of calling ko.toJSON() on the model. That way, your model still contains the property but what you send has the properties removed.

var Person = function(id, name, country) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.country = ko.observable(country); 

    self.toJSON = function () {
        var data = ko.toJS(self); // get the values of this model
        // delete the property from the data
        delete data.country;
        return data;
    };
};

var person = new Person(1, 'foo', 'bar');
var data = ko.toJSON(person); // {"id":1,"name":"foo"}

Upvotes: 0

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

You have to delete this property from all objects:

this.SaveDetail = function() {
    ko.utils.arrayForEach(people(), function(item){
        delete item["country"];                 
    });
};

Here is working fiddle: http://jsfiddle.net/nZDrk/8/

Upvotes: 1

jbabey
jbabey

Reputation: 46647

You can use the delete keyword to remove a property from an object entirely:

var somePerson = new Person(1, 'blah', 'blah');
delete somePerson.country;
// send somePerson to the webservice

Upvotes: 1

Related Questions