我在概念验证方面遇到了麻烦。我想做的是单击按钮时出现jQuery对话框。对话框内容绑定(bind)到 View 模型,并且对话框调用json服务以检索一些数据以填充该 View 模型。
我的代码遇到两个问题:
$(function() {
var vmAccount = function() {
var self = this;
this.Accounts = ko.observableArray();
this.Name = ko.observable('Jimmy');
};
function DisplayDialog() {
$("#Dialog").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Search": function() {
SearchForCustomerAccounts();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
function SearchForCustomerAccounts() {
console.log("Name: " + vmAccount.Name);
$.ajax({
url: "api/CustomerSearchController/" + vmAccount.Name,
type: "GET",
dataType: "json",
success: function(data) {
DisplayResults(data);
}
});
}
function DisplayResults(data) {
vmAccount.Accounts.removeAll();
for (var i = 0; i < data.length; i++) {
vmAccount.Accounts.push(data[i]);
}
};
$("#butSearch").button().on("click", function() {
DisplayDialog();
});
$(document).ready(function() {
ko.applyBindings(vmAccount);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<body>
<button id="butSearch">Open</button>
<div id="Dialog" style="visibility: visible">
<form id="Account">
<p>Customer Name</p>
<input type="text" data-bind="value: Name" />
</form>
</div>
</body>
我是javascript和 knockout 的新手,所以可能缺少一些简单的多数民众赞成。感谢你们可以提供的任何帮助,谢谢!
最佳答案
1)您的vmAccount
是函数,但是您尝试像实例一样使用它。
2)要从KO的可观察值中获取值(value),则应将其称为(包装值(value))。
因此,请使用vmAccount.Name()
而不是vmAccount.Name
。
$(function() {
function VmAccount () {
var self = this;
this.Accounts = ko.observableArray();
this.Name = ko.observable('Jimmy');
};
var vmAccount = new VmAccount();
function DisplayDialog() {
$("#Dialog").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Search": function() {
SearchForCustomerAccounts();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
function SearchForCustomerAccounts() {
console.log("Name: " + vmAccount.Name());
$.ajax({
url: "api/CustomerSearchController/" + vmAccount.Name(),
type: "GET",
dataType: "json",
success: function(data) {
DisplayResults(data);
}
});
}
function DisplayResults(data) {
vmAccount.Accounts.removeAll();
for (var i = 0; i < data.length; i++) {
vmAccount.Accounts.push(data[i]);
}
};
$("#butSearch").button().on("click", function() {
DisplayDialog();
});
$(document).ready(function() {
ko.applyBindings(vmAccount);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<body>
<button id="butSearch">Open</button>
<div id="Dialog" style="visibility: visible">
<form id="Account">
<p>Customer Name</p>
<input type="text" data-bind="value: Name" />
</form>
</div>
</body>