【发布时间】:2015-07-19 02:50:35
【问题描述】:
我在概念验证方面遇到了一些问题。我正在尝试做的是在单击按钮时出现一个 jQuery 对话框。对话框内容绑定到视图模型,并且对话框调用 json 服务来检索一些数据以填充该视图模型。
我在这里的代码遇到了两个问题:
- 只有当 div 在初始页面加载时可见时,vmAccount 视图模型才会绑定
- vmAccount 视图模型在 SearchForCustomerAccounts 或 DisplayResults 中未定义,尽管它是它们的全局变量
$(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 和淘汰赛的新手,所以它可能缺少一些简单的东西。感谢你们提供的任何帮助,谢谢!
【问题讨论】:
-
您的代码 sn-p 缺少 jQuery UI
-
哎呀忘了使用 stackoverflow 编码 sn-p 工具添加该引用
标签: javascript jquery mvvm knockout.js