2014-01-06 36 views
1

可以通過使用backbone js模型來保存多部分表單嗎?多部分表格保存爲backbonejs中的屬性

如何使用文件數據表單數據相結合,並保存到模型

我設置模型的屬性,以及如何以包括屬性的文件數據。我將來自其中一個站點的代碼調整爲Forc Backbone以將屬性保存爲文件。我不能將它與我的形式

<form enctype="multipart/form-data"> 
    <input type="file" name="ImageData"> 
    <input type="text" name="UserName"> 
</form> 

型號

User = Backbone.Model.extend({ 
    readAvatar : function (file, callback) { 
    var reader = new FileReader(); // File API object for reading a file locally 
    reader.onload = (function (theFile, self) { 
     return function (e) { 
     // Set the file data correctly on the Backbone model 
     self.set({avatar_file_name : theFile.name, avatar_data : fileEvent.target.result}); 
     // Handle anything else you want to do after parsing the file and setting up the model. 
     callback(); 
    }; 
    })(file, this); 
    reader.readAsDataURL(file); // Reads file into memory Base64 encoded 
    } 
    attribute : function(attr) { 
     return Object.defineProperty(this.prototype, attr, { 
     get: function() { 
      return this.get(attr); 
     }, 
     set: function(value) { 
      var attrs; 

      attrs = {}; 
      attrs[attr] = value; 
      return this.set(attrs); 
     } 
     }); 
    }; 
}); 


    var form_data = form.serializeArray(); 

查看

this.model.data = form_data; 
var profiledata;   
if (window.FormData) { 
     profiledata = new FormData(); 
     console.log(profiledata); 
} 

if (profiledata) { 
    jQuery.each($('#ImageData')[0].files, function(i, file) { 
     //reader.readAsDataURL(file); 
     profiledata.append("ImageData[]", file); 

    });  
} 
    this.model.ImageData = profiledata; 

    //and save the data 
    this.model.save 

回答

3

而不是模型處理FileReader邏輯,我一直在管理,在視圖。

檢查了這一點:

<form enctype="multipart/form-data"> 
    <input type="file" name="ImageData"> 
    <input type="text" name="UserName"> 
    <button>Submit</button> 
</form> 

查看:

var FormView = Backbone.View.extend({ 
    events: { 
    "submit form" : "submit", 
    "change input[type=file]" : "encodeFile" 
    }, 

    render: function() { 
    var content = this.template(); 
    this.$el.html(content); 
    return this; 
    }, 

    encodeFile: function (event) { 
    var file = event.currentTarget.files[0]; 
    var reader = new FileReader(); 
    reader.onload = function (fileEvent) { 
     this.model.set({ 
     avatar_data: fileEvent.target.result // file name is part of the data 
     }); 
    }.bind(this) 
    reader.onerror = function() { 
     console.log("error", arguments) 
    } 
    reader.readAsDataURL(file); 
    }, 

    submit: function (event) { 
    event.preventDefault(); 
    this.model.set({ UserName: $('input[name=UserName]').val() }); 
    this.model.save(); 
    } 
}); 
+0

凡'fileEvent'在這一行'avatar_data初始化:fileEvent.target.result'? – chridam

+1

好問題!它不是:)我的意思是e和fileEvent指向相同的東西。我要更新是正確的。 – w1zeman1p