简体   繁体   中英

KnockoutJS not binding

I cant seem to get the binding to work on my KnockoutJS app.

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

Here is the format of my JSON (generated by using <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
      }
    ]
  }
]

And here is how i am trying to call it in the page

<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

neither of those bindings work.

I create the forms object here

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

i hope your are expecting something like this

Working fiddle here

Now if you change something in textboxes in preview you can see automatic updates ie mapping does make things back to ko way .

View Model :

 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

       }

View :

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM