我有一个 html 文件,其中包含几个 js 文件。这些js文件具有 knockout 的视频模型,我需要将它们嵌套在html文件中绑定(bind)。
这是一个示例:
HTML
<div id="container1">
<span data-bind="html: name"></span>
<div id="container2">
<span data-bind="html: color"></span>
</div>
</div>
JavaScript
// Script comming from myScript1.js....
var person = new function() {
var viewModel = function() {
var self = this;
self.name = ko.observable("John");
return {
name: self.name
};
};
var vm = new viewModel();
ko.applyBindings(vm, document.getElementById("container1"));
}
// Script comming from myScript2.js....
var colors = new function() {
var viewModel = function() {
var self = this;
self.color = ko.observable("Red");
return {
color: self.color
};
}
var vm = new viewModel();
ko.applyBindings(vm, document.getElementById("container2"));
}
我收到此错误:
Uncaught ReferenceError: Unable to process binding "html: function (){return color }" Message: color is not defined
我该如何解决这个问题?谢谢!
最佳答案
嗯,我看到有两种方法可以解决这个问题。然而,在这两种解决方案中,js 文件的顺序都很重要(不太确定它对您是否重要)。
将颜色包含在人物中
使用with binding对于你的内部 html block :
标记:
<div id="container1">
<span data-bind="html: name"></span>
<!--with binding to set context-->
<div data-bind="with: colors">
<span data-bind="html: color"></span>
</div>
</div>
第一个文件:
// It's important to put this script first to make it available in person
var Colors = function() {
return {
color: ko.observable("Red")
};
}
第二个文件:
var Person = function() {
return {
name: ko.observable("John"),
// Create new instance of colors inside your person view model.
colors: new Colors()
};
};
ko.applyBindings(new Person(), document.getElementById("container1"));
使用内部 html 组件
您可以使用components分离页面上特定 block 的逻辑。我更喜欢这个解决方案来使应用程序更具可扩展性。
标记:
<div id="container1">
<span data-bind="html: name"></span>
<!--separate component as inner element-->
<colors></colors>
</div>
第一个文件(您的组件):
ko.components.register("colors", {
viewModel: function(params) {
return {
color: ko.observable("Red")
};
},
template: "<div id='container2'><span data-bind='html: color'></span></div>"
});
第二个文件:
var Person = function() {
return {
name: ko.observable("John")
};
};
ko.applyBindings(new Person(), document.getElementById("container1"));
关于javascript - 当来自单独的 js 文件时,如何嵌套 knockoutjs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44963067/