通过ajax发送淘汰js ViewModel作为数据

时间:2012-11-27 10:16:03

标签: json model knockout.js

用于使用以下ViewModel的数据填充搜索表单:

 function AppViewModel() {
    var self = this;
    self.Countries =[{"id": "1","name": "Russia"},{"id": "2","name": "Qatar"}];
    self.selectedCountryId =ko.observable();      
 }

我需要填充dropdwonlist的国家/地区列表。 当用户填写表单并单击“发送”时,我需要提交数据,但我不需要发送国家/地区列表! (仅限SelectedCountryId)

var vm=new AppViewModel();
ko.applyBindings(vm);

$('button').click(function(){

  console.log(ko.mapping.toJSON(vm));

}); 

有没有办法摆脱国家名单而不构建新的ViewModel用于发送?

2 个答案:

答案 0 :(得分:1)

Observable就像普通函数一样,所以你只需要从外面调用它。

function AppViewModel() {
    var self = this;
    self.Countries =[{"id": "1","name": "Russia"},{"id": "2","name": "Qatar"}];
    self.selectedCountryId = ko.observable('1');      
}

$(function() {
    var vm = new AppViewModel();
    ko.applyBindings(vm);

    $('button').click(function(){
      console.log(vm.selectedCountryId()); // plain
      console.log(ko.toJSON(vm.selectedCountryId())); // json
    });
});

http://jsfiddle.net/DiegoVieira/6kZMj/4/

答案 1 :(得分:0)


请查看我为您创建的演示Click here for the DEMO


更新了演示Click here for the updated Demo

HTML代码

<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<br/>
<label data-bind="text: selectedChoice"></label>


Javascript代码

var CountryModel = function(data){
  var self = this;
  self.id = ko.observable(data.id);
  self.name = ko.observable(data.name);
};
var viewModel = function(data) {
  var self = this;
  self.selectedChoice = ko.observable();
  self.countries = ko.observableArray([
      new CountryModel({id: "1", name: "Russia"}),
      new CountryModel({id: "2", name: "Qatar"})]);
};

ko.applyBindings(new viewModel());


START UPDATE

更新内容:

HTML代码:
在事件上添加按钮单击它调用sendMe函数,该函数返回selectedCountryId

的json对象
<input type="button" data-bind="click: sendMe, enable: selectedChoice" Value="Click Me"/>


Javascript代码

self.sendMe = function(){

    alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};


END UPDATE
START UPDATE1
这是关于避免添加模型的最后评论的更新,在这种情况下,让我们跳过CountryModel
因此, Javascript代码将如下:

var viewModel = function(data) {
   var self = this;
   self.selectedChoice = ko.observable();
   self.countries = ko.observableArray([
        {id: "1", name: "Russia"},
        {id: "2", name: "Qatar"}]);
    self.sendMe = function(){
        alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
    };
};

ko.applyBindings(new viewModel());

END UPDATE1

希望,它会帮助你。
感谢。