【问题标题】:How do I nest knockoutjs when comming from seperate js files?来自单独的 js 文件时如何嵌套 knockoutjs?
【发布时间】:2017-12-11 07:07:30
【问题描述】:

我有一个包含多个 js 文件的 html 文件。这些js文件有淘汰的视频模型,我需要绑定它们嵌套在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"));
}

jsfiddle

我收到此错误:

Uncaught ReferenceError: Unable to process binding "html: function (){return color }" 消息:颜色未定义

我该如何解决这个问题?谢谢!

【问题讨论】:

  • 我不熟悉在视图模型中使用匿名对象。您可以尝试将您的 JS 移动到 html 下方或上方,看看是否会有所不同?

标签: javascript knockout.js


【解决方案1】:

嗯,我看到了解决这个问题的两种方法。然而,在这两种解决方案中,js 文件的顺序都很重要(不太确定它对您是否重要)。

在人物中加入颜色

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"));

为你的内部 html 使用组件

您可以使用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"));

【讨论】:

  • 感谢您的详细帮助! “组件”方式看起来像是一个可能的解决方案 - 我将对此进行测试。再次感谢你。 :)
猜你喜欢
  • 2018-05-11
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多