4

클라이언트 용 백본과 서버용 Node.js를 사용하여 간단한 파일 브라우저를 개발하려고합니다. 순간 나는 그것이모델 내의 백본 컬렉션 + Node.js를 사용한 편안한 서버 디자인

클라이언트 코드를 하위 폴더로 올 때 모델을 설계하는 방법에 꽤 붙어있어 보이는

app.MyFile = Backbone.Model.extend({ 
    defaults: { 
     path: '', // id of the model will be the path + filename 
     content: '', // content of the file 
     isDir: false // if file is a directory 
    } 
}); 

var MyFileList = Backbone.Collection.extend({ 
    model: app.MyFile, 
    url: '/api/files' 
}); 

// create global collection of files 
app.MyFiles = new MyFileList(); 

// displays file name 
var MyFileItemView = Backbone.View.extend({ 
    events: { 
     'click .clickable': 'view' 
    }, 

    ... 

    view: function (source) { 
     if (this.model.toJSON().isDir) { 
      this.model.fetch(); 
      // XXX what to do here 

      _.each(this.model.get('content'), function (obj) { 
       console.log(obj.toJSON()); // error - no toJSON method 
      }); 

     } else { 
      // calls another view that calls the model.fetch 
      // to display the content (no issue here) 

     } 
    }, 
}); 


var MyFilesListView = Backbone.View.extend({ 
    initialize: function() { 
     // XXX Not sure if I should listen on MyFiles collection... 
     app.MyFiles.on('reset', this.render, this); 
    }, 

    render: function() { 
     app.MyFiles.each(function (file) { 
     new MyFileItemView({model:file}); 
     }, this); 

}); 

app.AppView = Backbone.View.extend({ 
    initialize: function() { 
    // fetch all files 
    app.MyFileList.fetch(); 
    } 
}); 

// app.js (point of entry) 
$(function() { 
    // Kick things off by creating the **App**. 
    new app.AppView(); 
}); 

내 서버 코드 같은 : 순간

var express = require("express"), 

... 

app.get('/api/files', function(req, res) { 
    ... 
    // return file list (including folder - no issue here) 
} 

app.get('/api/files/:id', function(req, res) { 
    var fileModel = createFileModel(req.params.id); // create file model 

    if (!fileModel.isDir) { 
     // if file is not directory, then simply read the content and return 
     // it back to the client -- no issue 
     ... 
    } else { 
     var files = []; 
     // read the directory to find all the files and push it to 
     // files array 
     ... 

     fileModel.content = files; 
     res.send(fileModel); 
    } 
} 

I 이 일을하는 올바른 방법이 무엇인지 모르겠습니다. 내 질문 :

  1. 모델 개체 자체를 나타내는 법. isDir===true의 경우 MyFile 컬렉션에 콘텐츠를 설정해야합니까? 이 경우 어떻게해야합니까? toJSON이 정의되어 있지 않으므로 toJSON() 모델의 콘텐츠를 호출하면 예외가 발생합니다.
  2. MyFilesListView 또한 글로벌 컬렉션도 청취해야합니까? 이제는 하위 폴더를 처리해야하므로 제대로 보이지 않습니다.
  3. 하위 폴더를 보려고 할 때 전역 컬렉션을 덮어 써야합니까?
  4. 내 서버 코드 구현이 정확합니까? 지금 내가 겪고있는 문제는 콘텐츠를 배열에 넣고 fileModel을 다시 클라이언트에 보내면 파일 목록이 모델 자체에 반영되지 않는다는 것입니다. parse을 재정의해야할까요?

는 여기

Nested models of the same 'class' in the Backbone.js framework?

  • Backbone: fetch collection from server 일부 게시물을 읽어하지만 ... 자바 스크립트가 혼란 여전히 적용하는 방법을 잘 모르겠어요 : (

  • 답변

    1

    단일 모델 (이 모델을 호출 할 수있는 xfile 모델)에서 이와 같은 간단한 함수로 모델 내에 간단한 모델을 작성할 수 있습니다.) :

    loadFolders : function() { 
        if (this.get('isDir')) { 
         var self = this; 
         self.subFolders = []; 
         _.each(self.get('files'), function(data) { 
         file = new File(data); 
         self.subFolders.push(file); 
         }); 
        } 
        } 
    

    정확한 렌더링을 위해 올바른보기를 사용하십시오.

    그리고 express.js 백엔드 (나는이 프레임 워크에 익숙하지 않다)에서 백본 모델에 적절한 json을 보내면된다.

    데이터가 너무 길고 각 모델 디렉토리를 별도로 가져오고 싶다면 (사용자가보기에서 폴더를 펼칠 때) 동일한 아이디어로 많은 컬렉션 (또는 컬렉션이 많은 컬렉션)이있는 모델을 만들 수 있습니다. 모델의 서버에서 데이터를 가져오고 백엔드는/api/file/folder1/folder2/file1과 같은 디렉토리를 지원해야합니다.

    (같은 기능을 제공하는 모든 백본 확장에 의해) 관계형 모델을 사용하고 더 마법의 일을 할 수있는 또 다른 방법 TXT

    당신에 대해 더 읽고 싶다면 :

    A marionette.js example that do the same

    Backbone.Relational - a relational extension for bakcbone

    추신 : 더 많은 링크를 제공 할 수 없으므로 Backbone.associate를 검색 할 수 있습니다. 백본의 다른 관계형 확장입니다.

    PS 2 : coffeescript를 사용하면 JavaScript 구문을보다 간단하고 쉽게 읽을 수 있습니다.