2013-02-08 35 views
1

我想將一個按鈕的值綁定到我的空白viewmodel,我該怎麼做呢?我做了這個fiddle來演示我想要實現的功能。數據綁定按鈕的值查看模型KnockoutJS

這裏是我的ViewModel:

var CustomerSearchViewModel = { 
    SearchType: ko.observable(""), 
    SearchString: ko.observable(""); 
} 

$(document).ready(function() { 
    ko.applyBindings(CustomerSearchViewModel); 
}); 

這裏是我正在試圖做的數據綁定:

<button type="button" data-bind='value: SearchType, valueUpdate: "afterkeydown"' value="0" class="btn" data-toggle="button">Company Name</button> 

回答

4

有多種方式來解決這個問題,但你如何嘗試的方式使用value與按鈕綁定將無法正常工作。

一個需要在你的HTML最少修改的最簡單的解決方案是使用click綁定,並設置SearchType在事件處理程序:

var CustomerSearchViewModel = { 
     SearchType: ko.observable(""), 
     SearchString: ko.observable(""), 
     setSearchType : function(data, element) 
     {   
      this.SearchType($(element.target).val()); 
     } 
    }; 

那麼你的按鈕應該是這樣的:

<button type="button" data-bind='click: setSearchType' 
     value="0" class="btn" data-toggle="button">Company Name</button> 

演示JSFiddle

0

我建議在創建模型是這樣的:

function CustomerSearchViewModel = { 
    SearchType: ko.observable(""), 
    SearchString: ko.observable(""), 
    UpdateSearch: function(data, event) { 
     this.SearchType($(event.target).val()); 
     this.SearchString($(event.target).attr('searchString')); 
    } 
} 

$(document).ready(function() { 
    ko.applyBindings(CustomerSearchViewModel); 
}); 

然後在綁定添加一個單擊事件更新SearchString,使用稱爲searchString自定義屬性。類似這樣的:

<button type="button" data-bind='click: UpdateSearch' searchString="Company Name" class="btn" value="0" data-toggle="button">Company Name</button>