如何使用knockout绑定数据绑定中的多个事件

时间:2017-05-23 02:03:44

标签: knockout.js data-binding

新手在这里淘汰JS。我还在学习东西。我试图在单个数据绑定中绑定多个事件。我怎样才能实现这一目标?我需要在单个事件上执行2个函数。

HTML

<span class="btn btn-default btn-file btn-primary">Browse<input type="file" id="ImportFile" data-bind="value:file,event: { change: $root.Browse }"></span>

功能#1

function Browse(data) {

        var data = new FormData();
        var files = $("#ImportFile").get(0).files;
        if (files.length > 0) {
            $("#tab1").removeClass("active");
            $("#tab2").addClass("active");

            $("#tabSelect").removeClass("active");
            $("#tabImport").addClass("active");

            fileName(files[0].name);
            data.append("UploadedFile", files[0]);


            self.changeMethod = function (data, event) {
                self.file(event.currentTarget.files[0]);
                self.fileSize(event.currentTarget.files[0].size);
            }

        }

    }

功能#2

self.fileChange=function(data){    
    if (window.File && window.FileReader && window.FileList && window.Blob)
    {
        //get the file size and file type from file input field
        var fsize = data.size;
        var ftype = data.type;

        if(fsize>10)
        {
            alert(fsize +" bites\nToo big!");
            self.file("")
        }

       switch(ftype)
        {
            case 'image/png':
            case 'image/gif':
                break;
            default:
                alert('Unsupported File!');
               self.file("")
        }
    }else{
        alert("Please upgrade your browser, because your current browser lacks some new features we need!");
    }
    };

1 个答案:

答案 0 :(得分:2)

您可以提供另一个功能,并从新功能中调用您要调用的2个功能。

这是一个示例

var viewModel = function() {
  var self = this;
  self.isFirstMethodCalled = ko.observable(false);
  self.isSecondMethodCalled = ko.observable(false);
  self.triggerFirstAndSecondMethods = function(data){
    self.firstMethod(data);
    self.secondMethod(data);
  };
  self.firstMethod = function(data){
    self.isFirstMethodCalled(true);
  }
  self.secondMethod = function(data){
    self.isSecondMethodCalled(true);
  }
};

ko.applyBindings(new viewModel()); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<input type="button" data-bind="click: triggerFirstAndSecondMethods" value="Call First And Second Method"/>
<div data-bind="visible: isFirstMethodCalled">
  First Method has been called.
</div>
<div data-bind="visible: isSecondMethodCalled">
  SecondMethod has been called.
</div>

相关问题