我正在开发一个包含JQuery项目和Knockout项目的网页。
基本上该视图有一个选择字段和一个由选择值更改更新的sevond视图。
我还有一个带有jquery自动完成功能的文本框搜索字段。
我想要做的是当我在搜索框后按Enter键时,javascript将更新ko.observable值并触发其更新,但它无效。我设法触发了按键,但我无法更新并触发更新..
下面是代码:
function Station(data){
var self = this;
this.userId = ko.observable(data.userid);
this.displayName = ko.observable(data.displayName);
this.email = ko.observable(data.email);
this.redirectURL = ko.computed(function(){
return "/someurl/somerequest?userId="+self.userId();
});
this.selectText = ko.computed(function(){
return self.displayName();
})
}
function currentStation(index)
{
return self.stations()[index];
}
function StationViewModel(){
var self = this;
self.stations = ko.observableArray([]);
$("#stationSelect").attr("disabled,true");
$.getJSON("@{someurl.getStationList()}",function(allData){
var mappedStations = $.map(allData,function(item)
{
return new Station(item);
});
self.stations(mappedStations);
$("#stationSelect").attr("disabled,false");
});
url = "/someurl/somerequest?userId=";
this.selectedStation = ko.observable();
this.redirectToStation = function(){
var linkToSend =
alert(self.selectedStation.redirectURL());
}
<!-- THIS IS THE CODE THAT HAS TO UPDATE THE FIELD BUT IT DOESN'T-->
this.getStation = function(event)
{
for(i = 0; i<this.stations().length;i++)
{
if(this.stations()[i].userId()==$("#search").val())
{
self.selectedStation = ko.observable(this.stations()[i]); //Am i doing it right?
}
}
};
}
<!-- This is the code That handles the click event inside the textbox. its working -->
ko.bindingHandlers.executeOnEnter = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
$(element).keypress(function (event) {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
allBindings.executeOnEnter.call(viewModel);
return false;
}
return true;
});
}
};
ko.applyBindings(new StationViewModel());
</script>
答案 0 :(得分:1)
而不是
self.selectedStation = ko.observable(this.stations()[i]);
做
self.selectedStation(this.stations()[I]);
希望这有帮助!
答案 1 :(得分:0)
我过去为了让Enter键正常工作而做的是将<input>
包裹在<form>
标记中
所以来自
<input type="text" data-bind="value:myValue"></input>
到
<form>
<input type="text" data-bind="value:myValue"></input>
</form>