[英]How do I include knockout viewmodel defined in separate javascript file in my view?
I am new to using knockout and I have created a view model that was originally in my view which worked and updated the text as I entered into the textbox but after I moved the knockout viewmodel from my view into a separate javasctipt file and included it in the view referencing it in the script tags the knockout bindings are not applied. 我是使用剔除的新手,我创建了一个视图模型,该视图模型最初在我的视图中使用,并在我输入文本框时更新了文本,但是在将剔除视图模型从视图移至单独的javasctipt文件并将其包含在其中之后在脚本标签中引用该视图的视图未应用敲除绑定。 What else do I need to do?
我还需要做什么? How do I get this to work?
我该如何工作? I don't want to have script tags in every view referencing knockout and having the view models defined in the view, I want the view models in separate files.
我不想在每个引用淘汰赛的视图中都具有脚本标签,并且不想在视图中定义视图模型,我希望视图模型位于单独的文件中。
Here is my view model which worked when I include it within script tags in my view. 这是我将视图模型包含在脚本标记中时起作用的视图模型 。 I have moved it to a separate file called
UserDashboardViewModel.js
and including it in my view but it does not work when in a separate file, only when included in the view: 我已经将其移动到名为
UserDashboardViewModel.js
的单独文件中,并将其包含在我的视图中,但是在单独文件中,仅当包含在视图中时,它才起作用:
var viewModel = {
monkey: ko.observable(),
array: ko.observableArray(),
AddAnimal: function ()
{
this.array.push(this.monkey());
}
};
ko.applyBindings(viewModel);
And in my view: 在我看来:
<script type='text/javascript' src='~/Scripts/knockout-3.4.0.js'></script>
<script type='text/javascript' src='~/Scripts/UserDashboardViewModel.js></script>
<h1 data-bind="text: monkey">text</h1>
... other knockout data-bindings that do not work
If your script tags are in the head
of your HTML
page then you need to make sure you call ko.applyBindings()
when the DOM is loaded. 如果脚本标记位于
HTML
页面的head
,则需要确保在加载DOM时调用ko.applyBindings()
。
// with jQuery
$(document).ready(function(){ko.applyBindings(viewModel); });
// shorter jQuery version
$(function(){ ko.applyBindings(viewModel); });
// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){
ko.applyBindings(viewModel);
}, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.