how to make bindings work when we add html at run

2019-09-04 07:00发布

问题:

I am working on Knockout bindings with breeze JS. While adding data to database for some entries by using breeze controller, I am trying to display few more fields related to one particular attribute which is required while storing data into my local database. So I created a custom binding which makes me do that. But I found that the fields I am adding in my view does not bind with my observable which I am using while creating a new entry

Here is the knockout binding

 ko.bindingHandlers.htmlTags = {

    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
         var value = valueAccessor();
        var valueUnwrapped = ko.unwrap(value);
        var x = "[ABC, 'XYZ','UVW']";
        var jt = bindingContext.$data.type._latestValue; // get the latest value of observable "Type" which is coming from database via breeze
        var finalHtmlTag = ko.observable("");
// Strings of HTML which I want to add while execution           
 var op = "<label>Operation to perform  :</label><select data-bind= \"options:"+ x +" , value: operation\"></select>";
            var cust = "<label>Customer Name :</label><input data-bind=\"value: customer\" placeholder=\"[Customer Name]\"></input>";
            var cust1 = "</div><div><label> Customer Name:</label><input  data-bind=\"value: customer\" placeholder=\"[Customer Name]\"></input>";
            var loc = "</div><div><label>Copy Location :</label><input data-bind=\"value: copyLocation\" placeholder=\"[Copy Location]\"></input>";
            if (jt === 1) { finalHtmlTag = op + cust1; }
            if (jt === 2) { finalHtmlTag = op; }
            if (jt === 3) { finalHtmlTag = cust + loc; }

            // Now manipulate the DOM element

                $('#addTag').html(finalHtmlTag); // Make the element visible

    }
};

//Key Value pair

 var typesX = [
        { key: 0, value: 'Type1' },
        { key: 1, value: 'Type2' },
        { key: 2, value: 'Type3' },
        { key: 3, value: 'Type4'}];

// My html //'job' is an observable which is used creating an instance with the help of breeze for storing a particular entry in local DB.

<form>
        <div data-bind="with: job"> 
            <div>
                <label>Job Name :</label>
                <input data-bind="value: jobName" placeholder="[JobName]" />
            </div>
            <div>
                <label>Type  :</label>
                <select data-bind="htmlTags: true, options: $root.typesX, optionsText: 'value', optionsValue: 'key', value: $data.type" />
            </div>
               <div>
                <label>User ID:</label>
                <input type="text" placeholder="[User ID]" data-bind="value: userID" />
            </div>
            <div id="addTag"></div>
//till here everything works fine but after this line bindings are not working properly
            </div>