1

用我使用以下 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 来发送?

4

2 回答 2

1

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

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

​</p>

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

于 2012-11-27T11:17:44.853 回答
0


请查看我为您创建的这个演示点击这里查看演示


更新的演示单击此处获取更新的演示

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());


开始更新

更新内容:

HTML 代码:
在事件 Click 上添加按钮它调用sendMe返回 json 对象的函数selectedCountryId

<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

希望对您有所帮助。
谢谢。

于 2012-11-27T11:34:39.270 回答