2013-07-05 129 views
0

我的應用程序允許用戶管理他們的文檔。當創建一個用戶時,用戶必須手動輸入文檔內容或從他們的計算機中選擇一個文件(這會將許多格式轉換爲用戶的HTML)。解決疑慮的正確方法是?

目前,我有一個簡單FileUploaderView這基本上是一個<input type="file">偵聽到文件的變化,並與像{ file: { type: SOME_TYPE' }, content: SOME_CONTENT }對象更新視圖的value財產。

然後,DocumentsNewController偵聽其中的更改並將支持的文件轉換爲HTML,並將結果放入文檔正文中。

但是,這樣做感覺簡直是錯誤的,不允許簡單的重用(我希望能夠做到)。

App.DocumentsNewController = Ember.ObjectController.extend 
    # ... stuff ... 

    handleDocumentUpload: (-> 
    doc = @get 'documentUpload' 
    return unless doc 

    Ember.run => 
     @set 'uploadError', false 
     @set 'unsupportedFile', false 
     @set 'processingUpload', true 

    type = doc.file.type 
    text = '' 

    try 
     if type.match /^text\// 
     text = doc.content 
     # Convert new lines to br's and paragraphs 
     text = '<p>' + text.replace(/\n([ \t]*\n)+/g, '</p><p>').replace('\n', '<br />') + '</p>' 
     else if type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
     text = new DOCX2HTML(doc.content).convert() 
     else 
     @set 'unsupportedFile', true 
    catch error 
     @set 'uploadError', true 
    finally 
     @set 'text', text 
     Ember.run => @set 'processingUpload', false 
).observes 'documentUpload' 

而且模板是一樣的東西

... stuff ... 

{{view App.FileUploaderView valueBinding="documentUpload" accept="text/*"}} 

什麼是正確的方式來重構文件轉換的東西了控制器的?

我希望能夠做一些事情,如:

{{documentHandler resultBinding="documentUpload"}} 

,並在控制器

App.DocumentsNewController = Ember.ObjectController.extend 
    # ... stuff ... 

    handleDocumentUpload: (-> 
    if doc = @get 'documentUpload' 
     @set 'text', doc 
).observes 'documentUpload' 

我首先想到的是讓一個DocumentHandlerView這將顯示輸入字段,顯示微調,顯示錯誤,解析文檔並將結果分配給result(並且由於控制器的模板具有resultBinding="documentUpload",HTML會觸發控制器的觀察者)。

使用視圖可以更容易重用,但我仍然認爲解析文檔不是視圖的工作。

有沒有更好的方法?

+0

在您的控制器中有邏輯接縫到目前爲止的正確位置 – intuitivepixel

+0

但我希望能夠在其他控制器中重用它。在我需要做文檔處理的每個控制器中複製它太奇怪了。 –

+0

你可以創建一個控制器混合,然後從中擴展你的控制器從 – intuitivepixel

回答

0

仔細閱讀您的問題後,最好記住的是創建一個Ember.Mixin,然後將其用於所有需要相同功能的控制器。

實施例從餘燼API docs採取:

App.Editable = Ember.Mixin.create({ 
    edit: function() { 
    console.log('starting to edit'); 
    this.set('isEditing', true); 
    }, 
    isEditing: false 
}); 

// Mix mixins into classes by passing them as the first arguments to 
// .extend. 
App.CommentView = Ember.View.extend(App.Editable, { 
    template: Ember.Handlebars.compile('{{#if isEditing}}...{{else}}...{{/if}}') 
}); 

commentView = App.CommentView.create(); 
commentView.edit(); // outputs 'starting to edit' 

的例子只是概念性的,但它會很容易自己創建一個mixin並把所有的公共邏輯在那裏。

希望它有幫助。

+0

是的,我想到了它 - 這是一個很好的方式來分享控制器之間的一些行爲。儘管如此,我並不完全確定處理文檔上傳是該控制器的工作。也許控制是一種方式? –

相關問題