我有来自我设置的 JSFiddle 的以下代码:https ://jsfiddle.net/ktce56hr/2/
var RootViewModel = function() {
var self = this;
this.rootText = ko.observable('default text');
this.rootFunc = function() {
alert("root func!");
};
}
ko.components.register('root', {
viewModel: function(model) {
var self = this;
this.rootViewModel = model;
this.title = ko.observable('default title');
},
template: { element: 'root_template' }
});
$(function () {
ko.applyBindings(new RootViewModel());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<div data-bind="component: { name: 'root', params: { model: $root } }"></div>
<script id="root_template" type="text/html">
<div>
<span data-bind="text: title"></div>
<div data-bind="with: rootViewModel">
<input type="text" data-bind="value: rootText" />
<button data-bind="click: rootFunc">Go</button>
</div>
</div>
</script>
运行此代码时,我收到以下错误:
Uncaught ReferenceError: Unable to process binding "with: function (){return rootViewModel }" Message: Unable to process binding "value: function (){return rootText }" Message: rootText is not defined
有人可以解释为什么我不能在组件视图模型上使用“rootViewModel”属性设置绑定上下文吗?