我有一个包含多个js文件的html文件。这些js文件有knockout videmodels,我需要将它们绑定在html文件中。
以下是一个示例:
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"));
}
我收到此错误:
未捕获的ReferenceError:无法处理绑定&#34; html:function (){return color}&#34;消息:颜色未定义
我该如何解决这个问题?谢谢!
答案 0 :(得分:0)
使用with binding作为内部html块:
标记:
<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"));
您可以使用components分隔页面上特定块的逻辑。我更喜欢这种解决方案,使应用程序更具可扩展性。
标记:
<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"));