【问题标题】:Knockout - Join Template with viewmodel淘汰赛 - 与视图模型连接模板
【发布时间】:2018-06-25 16:09:04
【问题描述】:

我正在尝试将视图模型与KnockoutJS 中的 html 页面相关联。

视图模型在外部文件中定义。并且 html 页面引用了这个视图模型。我正在使用requirejs 加载文件依赖项。

define(['knockout-latest'], function (ko) {
	var SimpleListModel = function(items) {
		this.items = ko.observableArray(items);
		this.itemToAdd = ko.observable("");
		this.addItem = function() {
			if (this.itemToAdd() != "") {
				this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
				this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
			}
		}.bind(this);  // Ensure that "this" is always this view model
	};
	 
	ko.applyBindings(new SimpleListModel(["Alpha", "Beta", "Gamma"]));
	//return SimpleListModel;
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" type="text/css" href="styles.css" />
		<script type="text/javascript" src="knockout-latest.js"></script>
		<script type="text/javascript" data-main="viewmodel" src="require.js"></script>
		<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
		<script type="text/javascript" src="viewmodel.js"></script>
	</head>	
<body>
<form data-bind="submit: addItem">
    New item:
    <input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
    <button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
    <p>Your items:</p>
    <select multiple="multiple" width="50" data-bind="options: items"> </select>
</form>
</body>
</html>

我收到以下错误: require.js:5 Uncaught Error: Mismatched anonymous define() module

我想知道如何在单独的文件中加入带有视图模型的 html 页面。

【问题讨论】:

    标签: javascript knockout.js requirejs


    【解决方案1】:

    查看您发布的代码,您可以看到页面上刚刚列出的脚本文件的链接。使用 RequireJS,脚本文件列表应该被删除,页面中应该只包含 RequireJS 和用于应用程序入口点的脚本。应用程序入口点可以是&lt;script&gt; 标记,也可以是RequireJS &lt;script&gt; 标记中的data-main 属性。

    我将您的代码复制到此example in plunker。我还将视图模型移动到knockout component 并使用RequireJS text plugin 加载HTML。在 main.js 中,有一个 require.config() 调用设置指向 CDN 的文本和敲除模块的路径。路径也可以指向本地文件,但请注意,用于敲除和文本的 &lt;script&gt; 标记不在 index.html 文件中。 RequireJS 会动态添加它们,因为它会根据 define() 调用确定依赖关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 2020-12-19
      • 1970-01-01
      • 2012-11-12
      • 2012-06-17
      相关资源
      最近更新 更多