I've been trying to use Knockout components with require.js for a project I've been working on. When I use the component it will display the HTML template, however the bindings within the template throw a reference error saying the field is undefined. I believe this is because 1. The viewModel is undefined, or 2. The viewModel is not bound to the template. However I cannot figure out how to fix it.
I am using the built-in server in phpStorm with Firefox developer edition
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'
}
);
*/
}
});
ComponentManager,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 define(['knockout', 'postbox', 'text!./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>
在您的admin-header
组件代码中,您需要返回一个viewModel
属性而不是viewmodel
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.