简体   繁体   English

单击击倒.js下载文件

[英]downloading a file on click in knockout.js

html html

<tbody data-bind="foreach: arrayList">
    <tr>
        <td><a href="#" data-bind="click: $parent.downloadLastFile">Download</a></td>
    </tr>
</tbody>

javascript javascript

    function ItemViewModel(item){
    if(!$.isEmptyObject(item)){
      var self = this;
      self.lastFile = ko.observable(item.file_name);    

      self.downloadLastFile = function(row) {
         console.log(row.lastFile());
         var link = document.createElement('a');
         link.href = data;
         link.download = row.lastFile();
         document.body.appendChild(link);
         link.click();
        }
     }
   }
function MainViewModel() {
    var self = this;
    self.arrayList= ko.observableArray();
}
dataModel = new MainViewModel();
ko.applyBindings(dataModel);

I am trying to download a file on clicking. 我正在尝试点击下载文件。 This piece of code is not working. 这段代码不起作用。 Can someone check? 有人可以检查吗?

  • I can't see self variable defined in your model. 我看不到模型中定义的self变量。
  • Since I see $parent in your click binding I assume there should be a parent model where you defined and assign data to ArrayList . 由于我在click绑定中看到$parent ,因此我假设应该有一个父模型,您可以在其中定义数据并将其分配给ArrayList
  • Since you are using knockout click binding you don't need to use jquery click binding inside knockout click function ("#download_div") again. 由于您使用的是knockout click binding您无需再次在剔除点击功能("#download_div")使用jquery单击绑定。 WRONG 错误

Below just is an example how you can do it 下面只是一个示例,您可以如何做

Example : https://jsfiddle.net/kyr6w2x3/114/ 范例: https : //jsfiddle.net/kyr6w2x3/114/

JS: JS:

var data = [{id:1, file_name : "file_name1"},{id:2, file_name : "file_name2"}];

function AppViewModel(){
   var self = this;
   self.ArrayList = ko.observableArray($.map(data, function (item) {
          return new ItemViewModel(item);
    }));

   self.downloadLastFile = function(item) {
     console.log(item.lastFile());
     var link = document.createElement('a');
    link.href = data;
    //here you append your rootURL to the file name
    link.download = item.lastFile();
    document.body.appendChild(link);
    link.click();
   }
 }

 var ItemViewModel = function(data){
   var self = this;
   self.lastFile = ko.observable(data.file_name);
 }

var viewModel = new AppViewModel();
ko.applyBindings(viewModel); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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