1

如果我定义对象

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

如何在按钮的单击事件中从此对象中删除属性“国家”。事情是,当我将数据发送到 web 服务时,我不想将此属性发送给它。

请在此处查看小提琴,我试图在保存按钮的单击事件上删除属性“国家”。 http://jsfiddle.net/kirannandedkar/nZDrk/7/

4

3 回答 3

1

您可以使用delete关键字从对象中完全删除属性:

var somePerson = new Person(1, 'blah', 'blah');
delete somePerson.country;
// send somePerson to the webservice
于 2012-12-19T20:00:25.593 回答
1

您必须从所有对象中删除此属性:

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

这是工作小提琴:http: //jsfiddle.net/nZDrk/8/

于 2012-12-19T20:05:38.767 回答
0

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"}
于 2012-12-19T22:28:27.807 回答