【问题标题】:bindingHandlers is not firing with knockoutbindingHandlers 没有通过淘汰赛触发
【发布时间】:2022-07-12 06:34:34
【问题描述】:

当输入类型文件更改并且数据已经创建(从模型中获取)时,我无法更新 fileSrc(bindingHandlers),只有在创建新元素时我才能看到当我更改文件时更新其他两个字段)

function PatientInsuranceCarrierImage(plainInsuranceImage) {
        var self = this;
        
        self.ImageSrcName = ko.observable(plainInsuranceImage.ImageSrcName);
        self.FileName = ko.observable(plainInsuranceImage.FileName);
              
    }
    
    function PatientInsuranceCarrierImageViewModel(items) {
        var self = this;
        
        self.PatientInsuranceCarrierImages = ko.observableArray(items.map(i => new PatientInsuranceCarrierImage(i)));
        
              
        const newPatientInsuranceCarrierImage = {
            FileName: "test",
            ImageSrcName: "asdfa",
        };

               
         // Operations
   
        self.addpatientInsuranceCarrierImage = function() {
            self.PatientInsuranceCarrierImages.push(new PatientInsuranceCarrierImage(newPatientInsuranceCarrierImage));
        }
        
    }
    
var plainImages = JSON.parse('[{\"FileName\":\"dtreal.png\",\"ImageSrcName\":\"dtreal\"}]');
var patientInsuranceCarrierImagesViewModel = new PatientInsuranceCarrierImageViewModel(plainImages);
    ko.applyBindings(patientInsuranceCarrierImagesViewModel);
    
    
    ko.bindingHandlers.fileSrc = {
        init: function (element, valueAccessor) {
            ko.utils.registerEventHandler(element, "change", function () {
                var reader = new FileReader();  
                //var $changed_input = $(this),
                //    file_extension = $changed_input.val().match(/\.([^\.]+)$/)[1].toLowerCase(),
                //    allowed_extensions = new RegExp($changed_input.attr('accept').replace(/,/g, "$|^").replace(/\./g, "").toLowerCase());

                //if (!file_extension.match(allowed_extensions)) {
                //    alert('Please do not try to upload files with the extension "' + file_extension + '".');
                reader.onload = function (e) {
                    var value = valueAccessor();
                    value.ImageSrcName(e.target.result);
                    value.FileName(element.files[0].name)
                }
                 
                reader.readAsDataURL(element.files[0]); 
            });
        },
        update: function (element, valueAccessor) {
            // This will be called once when the binding is first applied to an element,
            // and again whenever any observables/computeds that are accessed change
            // Update the DOM element based on the supplied values here.
            ko.utils.registerEventHandler(element, "change", function () {
                var reader = new FileReader();

                reader.onload = function (e) {
                    var value = valueAccessor();
                    value.ImageSrcName(e.target.result);
                    value.FileName(element.files[0].name)
                }

                reader.readAsDataURL(element.files[0]);
            });
        }
    };
    .thumbnail{
        height: 80px;
        margin: 10px; 
        float: left;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="float: right; vertical-align: top; padding-bottom: 5px;">
           <a data-bind="click: addpatientInsuranceCarrierImage" href="#" class="button">Add New Image</a>
</div>
        
<table id="patientInsuranceImages" style="width: 100%;" class="alt1">
        <thead>
            <tr>
              <th class="Table_Top" style="width: 100px; text-align: center;">
                        Preview
                    </th>
                    <th class="Table_Top" style="width: 80px; text-align: center;">
                        File Name
                    </th>  
                       <th class="Table_Top" style="width: 200px; text-align: center;">
                    </th>
            </tr>
        </thead>
         <!-- ko if: PatientInsuranceCarrierImages().length > 0 -->
        <tbody data-bind="foreach: PatientInsuranceCarrierImages">
            <tr>  
                    <td>
                        <img src="." class="thumbnail" data-bind="attr:{src:ImageSrcName}"/>
                    </td>
                    <td style="text-align: center;">
                        <input type="hidden" data-bind="value: FileName, attr:{name:'images[' + $index() + '].FileName'}" />
                        <span data-bind="text: FileName"></span>
                    </td>
                <td>
                     
              <input type="file"  
                            data-bind="fileSrc: { ImageSrcName: ImageSrcName, FileName: FileName }, attr: {name: 'images[' + $index() + '].InputFile'}" />
                </td>                
            </tr>    
        </tbody>
        <!-- /ko -->
    </table>

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    尝试此响应后,我执行相同操作并在处理程序下方应用绑定,它现在可以工作

    Knockout Custom Binding does not Init sometimes

        
        ko.bindingHandlers.fileSrc = {
            init: function (element, valueAccessor) {
                ko.utils.registerEventHandler(element, "change", function () {
                    var reader = new FileReader();  
                    //var $changed_input = $(this),
                    //    file_extension = $changed_input.val().match(/\.([^\.]+)$/)[1].toLowerCase(),
                    //    allowed_extensions = new RegExp($changed_input.attr('accept').replace(/,/g, "$|^").replace(/\./g, "").toLowerCase());
    
                    //if (!file_extension.match(allowed_extensions)) {
                    //    alert('Please do not try to upload files with the extension "' + file_extension + '".');
                    reader.onload = function (e) {
                        var value = valueAccessor();
                        value.ImageSrcName(e.target.result);
                        value.FileName(element.files[0].name)
                    }
                     
                    reader.readAsDataURL(element.files[0]); 
                });
            },
            update: function (element, valueAccessor) {
                // This will be called once when the binding is first applied to an element,
                // and again whenever any observables/computeds that are accessed change
                // Update the DOM element based on the supplied values here.
                ko.utils.registerEventHandler(element, "change", function () {
                    var reader = new FileReader();
    
                    reader.onload = function (e) {
                        var value = valueAccessor();
                        value.ImageSrcName(e.target.result);
                        value.FileName(element.files[0].name)
                    }
    
                    reader.readAsDataURL(element.files[0]);
                });
            }
        };
        
        
        function PatientInsuranceCarrierImage(plainInsuranceImage) {
            var self = this;
            
            self.ImageSrcName = ko.observable(plainInsuranceImage.ImageSrcName);
            self.FileName = ko.observable(plainInsuranceImage.FileName);
                  
        }
        
        function PatientInsuranceCarrierImageViewModel(items) {
            var self = this;
            
            self.PatientInsuranceCarrierImages = ko.observableArray(items.map(i => new PatientInsuranceCarrierImage(i)));
            
                  
            const newPatientInsuranceCarrierImage = {
                FileName: "test",
                ImageSrcName: "asdfa",
            };
    
                   
             // Operations
       
            self.addpatientInsuranceCarrierImage = function() {
                self.PatientInsuranceCarrierImages.push(new PatientInsuranceCarrierImage(newPatientInsuranceCarrierImage));
            }
            
        }
        
    var plainImages = JSON.parse('[{\"FileName\":\"dtreal.png\",\"ImageSrcName\":\"dtreal\"}]');
    var patientInsuranceCarrierImagesViewModel = new PatientInsuranceCarrierImageViewModel(plainImages);
        ko.applyBindings(patientInsuranceCarrierImagesViewModel);
        
    .thumbnail{
            height: 80px;
            margin: 10px; 
            float: left;
        }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div style="float: right; vertical-align: top; padding-bottom: 5px;">
               <a data-bind="click: addpatientInsuranceCarrierImage" href="#" class="button">Add New Image</a>
    </div>
            
    <table id="patientInsuranceImages" style="width: 100%;" class="alt1">
            <thead>
                <tr>
                  <th class="Table_Top" style="width: 100px; text-align: center;">
                            Preview
                        </th>
                        <th class="Table_Top" style="width: 80px; text-align: center;">
                            File Name
                        </th>  
                           <th class="Table_Top" style="width: 200px; text-align: center;">
                        </th>
                </tr>
            </thead>
             <!-- ko if: PatientInsuranceCarrierImages().length > 0 -->
            <tbody data-bind="foreach: PatientInsuranceCarrierImages">
                <tr>  
                        <td>
                            <img src="." class="thumbnail" data-bind="attr:{src:ImageSrcName}"/>
                        </td>
                        <td style="text-align: center;">
                            <input type="hidden" data-bind="value: FileName, attr:{name:'images[' + $index() + '].FileName'}" />
                            <span data-bind="text: FileName"></span>
                        </td>
                    <td>
                         
                  <input type="file"  
                                data-bind="fileSrc: { ImageSrcName: ImageSrcName, FileName: FileName }, attr: {name: 'images[' + $index() + '].InputFile'}" />
                    </td>                
                </tr>    
            </tbody>
            <!-- /ko -->
        </table>

    【讨论】:

      猜你喜欢
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 2017-05-11
      相关资源
      最近更新 更多