【发布时间】:2015-05-28 02:45:20
【问题描述】:
我一直在尝试将 Knockout 组件与 require.js 一起用于我一直从事的项目。当我使用该组件时,它将显示 HTML 模板,但是模板中的绑定会引发引用错误,指出该字段未定义。 我相信这是因为 1. viewModel 未定义,或者 2. viewModel 未绑定到模板。但是我不知道如何解决它。
我正在使用 phpStorm 中的内置服务器和 Firefox 开发者版
index.php
<?php
namespace project;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Project | Admin</title>
<link rel="stylesheet" href="css/grid.css"/>
<style>
</style>
</head>
<body>
<admin-header params=""></admin-header>
<script src="js/vendor/require.js" data-main="js/app"></script>
</body>
</html>
app.js
requirejs.config({
paths: {
jquery: 'vendor/jquery',
postbox: 'vendor/knockout-postbox',
domReady: 'vendor/domReady',
text: 'vendor/text',
knockout: 'vendor/knockout',
hashchange: 'vendor/hashchange',
underscore: 'vendor/underscore',
ComponentManager: 'components/ComponentManager'
},
shim: {
knockout: {
deps: ['jquery']
},
hashchange: {
deps: ['jquery']
},
underscore:{
exports: '-'
}
}
});
require(['knockout', 'AdminViewModel', 'domReady!'], function(ko, AdminViewModel){
ko.applyBindings(new AdminViewModel());
});
AdminViewModel.js
define(['knockout', 'postbox', 'ComponentManager'], function( ko, postbox, ComponentManager) {
return function AdminViewModel() {
var self = this;
self.pageTitle = ko.observable('Home').publishOn('pageTitle');
var componentManager = new ComponentManager();
componentManager.registerComponents(['admin-header']);
/*
// doesnt work when registered in the parent view either
ko.components.register(
'admin-header', {
require: 'components/admin-header/admin-header'
}
);
*/
}
});
组件管理器,js
define(['knockout', 'underscore', 'require'], function(ko, _, require){
return function ComponentManager() {
this.registerComponents = function(components) {
_.each(components, function (component) {
var componentPath = 'components/' + component + '/' + component;
console.log("registering: " + componentPath );
ko.components.register(component, {
require: componentPath
});
});
}
}
});
admin-header.js 定义(['淘汰赛','邮箱','文本!./admin-header_template.html'],
function(ko, postbox, template){
function AdminHeaderModel(params){
var self = this;
self.pageTitle = ko.observable('Title');//.subscripeTo('pageTitle', true, function(title){return title.toUpperCase()});
}
return {
viewmodel: AdminHeaderModel,
template: template
};
});
admin-header-template.html
<div>
<h1>Project</h1>
<h1 data-bind="text: pageTitle"></h1>
</div>
【问题讨论】:
标签: javascript mvvm knockout.js requirejs components