我正在尝试使用我所见过的网站和教程中的淘汰赛和网站制作一个SPA网站,以便分割网站,这不是一件巨大的事情。有一点我希望看到:
My first name is: Bryan
但相反,我得到了:
My first name is: function c(){if(0<arguments.length)return c.tb(c[E],arguments[0])&&(c.ga(),c[E]=arguments[0],c.fa()),this;a.l.oc(c);return c[E]}
从我的index.thml开始:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>asdf</title>
</head>
<body>
<mainview></mainview>
<!-- global imports -->
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.min.js"></script>
<script type='text/javascript' src="./index.js"></script>
</body>
</html>
我的index.js:
"use strict";
requirejs.config({
baseUrl: '',
paths: {
knockout: 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min',
text: 'https://cdnjs.cloudflare.com/ajax/libs/require-text/2.0.12/text.min'
}
});
ko.components.register(
'mainview',
{
require: './indexViewModel'
}
);
ko.applyBindings();
indexViewModel.js:
"use strict";
define(['knockout', 'text!./indexViewModel.html'], function(ko, htmlString) {
function indexViewModel(params)
{
var self = this;
self.firstName = ko.observable('Bryan');
}
return { viewModel: indexViewModel, template: htmlString };
});
最后我的indexViewModel.html:
<div>
<p>input name: <input data-bind="value: firstName"></input></p>
<p>My first name is: <span data-bind='text: firstName'></span></p>
</div>
所有这些都给出了我上面提到的结果。
现在,如果我将firstname
更改为firstName()
,那么它最初会出现正确,但如果我更改输入,则不会发生任何事情。
答案 0 :(得分:1)
因为在我的index.html上,我导入了knockout并且我从配置中将knockout设置为requirejs参数。
我找到了这个 Issue loading knockout components view model using requireJS 这让我陷入了困境。好的,所以我做了这些改动:
的index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Battlestations Character Generator</title>
</head>
<body>
<mainview></mainview>
<!-- global imports -->
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.min.js"></script>
<!-- no more knockout reference here -->
<script type='text/javascript' src="./index.js"></script>
</body>
</html>
现在是我的index.js:
"use strict";
requirejs.config({
baseUrl: '',
paths: {
knockout: 'https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min',
text: 'https://cdnjs.cloudflare.com/ajax/libs/require-text/2.0.12/text.min'
}
});
// "app main()"
requirejs(['knockout'], function(ko) {
var self = this;
ko.components.register(
'mainview',
{
require: './indexViewModel'
}
);
ko.applyBindings();
});
并将<input></input>
更改为<input />
,虽然没有改变,但如果这是“良好做法”,我会继续使用它。
在这些更改,重新加载,所有工作和更改输入之后立即更改<span>
耶!
答案 1 :(得分:0)
我知道答案已被接受,我在这里仅为已经尝试答案并失败的用户发布答案。我在MVC应用程序中也遇到了这个问题。问题是,我在_Layout.cshtml
和我的页面中都引用了_Layout.cshtml
文件。当我从default_includes
中删除JS引用并仅将其引用到页面时,一切都很好。干杯!