javascript - KnockoutJS 未绑定(bind)

标签 javascript jquery html knockout.js

我似乎无法让绑定(bind)在我的 KnockoutJS 应用程序上运行。

JSFIDDLE -> http://jsfiddle.net/maylortaylor/pfqnkj17/

这是我的 JSON 格式(使用 <pre data-bind="text: ko.toJSON($root.forms,null,2)"></pre> 生成)

[
  {
    "formTitle": "formTitle",
    "formDescription": "formDesc",
    "fieldTemplates": [
      {
        "fieldId": "text1",
        "title": "title",
        "description": "description fieldTemplate",
        "isReq": true
      },
      {
        "fieldId": "text2",
        "title": "ttitle22",
        "description": "description fieldTemplate 2",
        "isReq": false
      }
    ]
  }
]

这是我尝试在页面中调用它的方式

<div id="MiddleColumn">
            <input data-bind="textInput: $root.formTitle" type="text" placeholder="Title" class="span8 hideOffFocus input-full large-type">
        <input data-bind="textInput: formDescription" type="text" placeholder="Description" class="hideOffFocus input-full">
</div

这些绑定(bind)都不起作用。

我创建了 forms此处对象

var FormModel = function (forms) {
    var self = this;

    self.forms = ko.observableArray(ko.utils.arrayMap(forms, function (form) {
        return {
            formTitle: form.formTitle, formDescription: form.formDescription,
            fieldTemplates: ko.observableArray(form.fieldTemplates) };
    }));

};

ko.applyBindings(new FormModel(initialData));

最佳答案

我希望你期待这样的事情

工作 fiddle here

现在,如果您在预览中更改文本框中的某些内容,您可以看到自动更新,即 mapping 确实使事情回到 ko way 。

查看模型:

 var mapping = {
        'fieldTemplates': {
            create: function (options) {
                return new FormModel(options.data);
            }
        }
    }

function FormModel(forms) {
        var self = this;
        self.forms = ko.observableArray();
        ko.mapping.fromJS(forms, mapping, self);

       // other stuff

       }

查看:

<div id="MiddleColumn">
    <input data-bind="textInput: $root.formTitle" type="text" />
    <input data-bind="textInput: $root.formDescription" type="text"/><br/>
    <div data-bind="foreach:$root.fieldTemplates">
        <span data-bind="text:fieldId"></span> 
         <span data-bind="text:title"></span>
         <span data-bind="text:description"></span>
         <span data-bind="text:isReq"></span>
        <br/>
    </div>
</div>

关于javascript - KnockoutJS 未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27438671/

相关文章:

html - 未激活的移动边距错误 - Bootstrap

javascript - Angular ng-class中的css过渡淡入淡出

javascript - AngularJs onClick 防止滚动到顶部

javascript - 尝试加载自定义客户端编辑器时出错

javascript - 在屏幕加载时反向播放 html5 视频

jquery - Live() 关键字在加载动态 html 图像时不起作用

jquery - HoverCard 中的 Bootstrap 下拉按钮

html - 如何在表格单元格之间填充,而不是在整个表格周围填充?

javascript - 如何在 block 工作之前在 mocha 中获取断言?

javascript - 构造函数中闭包的神秘行为