// partial view
<%
'// serialising server model
Dim serialisedModel As String = Newtonsoft.Json.JsonConvert.SerializeObject(Model)
%>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.5.1.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/knockout-3.1.0.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/knockout.mapping.debug.js") %>">
<script type="text/javascript" src="<%= Url.Content("~/Scripts/SearchingViewModel.js") %>"></script>
<script type="text/javascript">
var data = <% Response.Write(serialisedModel) %>;
$(document).ready(function() { ko.applyBindings(new ViewModel(data)); });
</script>
// rest of html page
// SearchingViewModel.js
function ViewModel(data) {
var self = this;
/// lot of observable properties here but left out for brevity
/// Search viewModel
self.search = new Search(data);
} // end ViewModel
function Search(data) {
var self = this;
/// initiates a search
self.SearchData = function () {
$.ajax({
url: '/pathToGetSearchResults',
type: 'GET',
// etc, etc, etc,
};
}
}
// HTML bit
<input data-bind="click: search.SearchData" type="button" id="search-button" class="button" value="Search" />
我获取服务器模型,将其序列化并将其传递给视图模型,该模型位于SearchingViewModel.js脚本中。
问题是当页面加载时会激活ajax调用。 按键点击按钮时会触发但是 只有在点击事件被提升时才应该触发它?
如何阻止不受欢迎的行为?
答案 0 :(得分:1)
在我使用Knockout的时候,我注意到当我将它们放入点击装订中时,在页面加载时触发的这种行为的行为1.你在绑定中使用的变量是实际的功能而且2.当你穿上它时将变量包装在“function(){variable()}”中。
所以我想在你的HTML中看起来像这样:
<button data-bind="click: functionToRun">
你想要的是这个:
<button data-bind="click: function() { functionToRun() }">
编辑:啊,我没有看到你发布了你的HTML代码。这正是发生的事情。在按钮数据绑定中,只需将data-bind="click: search.SearchData"
更改为data-bind="click: function() { search.SearchData() }"
即可。那应该可以解决你的问题。
答案 1 :(得分:0)
Here is example and it works as well:
function ViewModel(data) {
var self = this;
/// lot of observable properties here but left out for brevity
/// Search viewModel
self.search = new Search(data);
} // end ViewModel
function Search(data) {
var self = this;
/// initiates a search
self.SearchData = function () {
console.log('handler fired');
}
}
ko.applyBindings(new ViewModel('test data'));
答案 2 :(得分:0)
我知道这是一个古老的问题,但我会想到这个根源。
var ViewModel = function() {
var self = this;
self.Search = function() {
/// do a search
///Ajax stuff
console.log('handler fired');
}
self.Init = function () {
//jquery stuff if needed
}
}
$(document).ready(function () {
var view = new ViewModel();
ko.applyBindings(view);
view.Init();
});
<input data-bind="click: Search" type="button" id="search-button" class="button" />