以下是我的HTML:
<ul class="nav navbar-nav pull-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" data-bind="text: fullName"></a>
<ul class="dropdown-menu">
<li><a href="#">Accounts & Settings</a></li>
<li><a href="#" data-bind="click: sout">Sign Out</a></li>
</ul>
</li>
</ul>
<div class="input-group">
<input type="text" class="form-control" id="hotels" placeholder="Search by Hotel Name or Hotel ID" data-bind='value: hotelName'>
<span class="input-group-btn">
<button class="btn btn-success disabled" type="submit" data-bind="css: enablebtn">Search</button>
</span>
</div>
我使用knockout.js文本绑定来获取anchor标记内的fullName值,并使用CSS绑定在两个计算的observable的帮助下启用禁用按钮。两个可比较的观察者中的任何一个都不起作用。
但是,如果我删除与CSS绑定相关的计算的observable,则文本绑定似乎完美无缺。
为什么我无法在Knockout.JS代码中添加两个计算变量的任何帮助?
以下是完成相同的Java Script代码:
$(document).ready(function(){
function appModel(session_info){
var temp = $.parseJSON(session_info);
this.userName = ko.observable(temp[0].user_name);
this.firstName = ko.observable(temp[0].first_name);
this.lastName = ko.observable(temp[0].last_name);
this.hotelName = ko.observable("");
this.fullName = ko.computed(function(){
return this.firstName() + " " + this.lastName();
}, this);
this.enablebtn = ko.computed(function(){
return this.hotelName().length() > 0 ? "enabled":"disabled";
}, this);
this.sout = function(){
$.ajax({
url:"../api/sessions.php",
type:"get",
data: {rqtype: '0'},
cache:false,
success:function(session_info){
var data = $.parseJSON(session_info);
if (data.status == 'Invalid_id'){
window.location.replace('../files/main.html');
}
}
});
}
};
$.ajax({
url:"../api/sessions.php",
type:"get",
data: {rqtype: '1'},
cache:false,
success:function(session_info){
var data = $.parseJSON(session_info);
if (data.status == 'Invalid_id'){
window.location.replace('../files/main.html');
} else {
ko.applyBindings(new appModel(session_info));
}
}
});
$(function(){
$("#hotels").autocomplete({
source:'../api/hotel_list_typehead.php',
minLength:2
});
});
});
仅供参考:示例JSON
(Session_info:{"user_name":"prad@ac.com","first_name":"saurabh","last_name":"pradhan"})
答案 0 :(得分:1)
string.length
是属性而不是函数。因此,您在()
中有一组额外的enablebtn
。
正确的版本应如下所示:
this.enablebtn = ko.computed(function(){
return this.hotelName().length > 0 ? "enabled":"disabled";
}, this);