2014-04-19 2 views
0

나는 이것에 관해서 많은 질문을 이미 해왔습니다. 구식 방법을 사용하는 오래된 질문 중 일부는 _.js 및 backbone.js의 최신 버전에서 작동하지 않으며 사실을 알려주기 위해 조금 잃어 버렸습니다.json 파일에서 템플릿으로 backbone.js 컬렉션

현재 backbone.js를 배우고, 잘 가고, MVC 등으로 좋은 습관으로 돌아갑니다. jQuery를 사용하여 게으르다.

어쨌든 ... 나는 몇 가지이 바이올린을 겪었 : http://jsfiddle.net/sushanth009/bBtgt/1/

var postsObject = [{ 
    "_id": "50f5f5d4014e045f000002", 
     "author": { 
     "name": "Chris Crawford", 
     "photo": "http://example.com/photo.jpg" 
    }, 
     "status": "This is a sample message.", 
     "comments": [{ 
     "_id": "5160eacbe4b020ec56a46844", 
      "text": "This is the content of the comment.", 
      "author": "Bob Hope" 
    }, { 
     "_id": "5160eacbe4b020ec56a46845", 
      "text": "This is the content of the comment.", 
      "author": "Bob Hope" 
    }] 
}, { 
    "_id": "50f5f5d4014e045f000003", 
     "author": { 
     "name": "Brown Robert", 
      "photo": "http://example.com/photo.jpg" 
    }, 
     "status": "This is another sample message.", 
     "comments": [{ 
     "_id": "5160eacbe4b020ec56a46846", 
      "text": "This is the content of the comment.", 
      "author": "Bob Hope" 
    }, { 
     "_id": "5160eacbe4b020ec56a46847", 
      "text": "This is the content of the comment.", 
      "author": "Bob Hope" 
    }] 
}]; 

// Comment Model 
var Comment = Backbone.Model.extend({ 
    idAttribute: '_id', 
    defaults: { 
     text: "", 
     author: "" 
    } 
}); 

// Comments collection 
var Comments = Backbone.Collection.extend({ 
    model: Comment 
}); 

// Author Model 
var Author = Backbone.Model.extend({ 
    defaults: { 
     text: "", 
     author: "" 
    } 
}); 

// Post Model 
var Post = Backbone.Model.extend({ 
    idAttribute: '_id', 
    defaults: { 
     author: "", 
     status: "" 
    }, 
    parse: function (resp) { 
     // Create a Author model on the Post Model 
     this.author = new Author(resp.author || null, { 
      parse: true 
     }); 
     // Delete from the response object as the data is 
     // alredy available on the model 
     delete resp.author; 
     // Create a comments objecton model 
     // that will hold the comments collection 
     this.comments = new Comments(resp.comments || null, { 
      parse: true 
     }); 
     // Delete from the response object as the data is 
     // alredy available on the model 
     delete resp.comments; 

     // return the response object 
     return resp; 
    } 
}) 
// Posts Collection 
var Posts = Backbone.Collection.extend({ 
    model: Post 
}); 

var PostsListView = Backbone.View.extend({ 
    el: "#container", 
    renderPostView: function(post) { 
     // Create a new postView 
     var postView = new PostView({ 
      model : post 
     }); 
     // Append it to the container 
     this.$el.append(postView.el); 
     postView.render(); 
    }, 
    render: function() { 
     var thisView = this; 
     // Iterate over each post Model 
     _.each(this.collection.models, function (post) { 
      // Call the renderPostView method 
      thisView.renderPostView(post); 
     }); 
    } 
}); 


var PostView = Backbone.View.extend({ 
    className: "post", 
    template: _.template($("#post-template").html()), 
    renderComments: function() { 
     var commentsListView = new CommentsListView({ 
      // Comments collection on the Post Model 
      collection : this.model.comments, 
      // Pass the container to which it is to be appended 
      el : $('.comments', this.$el) 
     }); 
     commentsListView.render();   
    }, 
    render: function() { 
     this.$el.empty(); 
     // Extend the object toi contain both Post attributes 
     // and also the author attributes 
     this.$el.append(this.template(_.extend(this.model.toJSON(), 
      this.model.author.toJSON() 
     ))); 
     // Render the comments for each Post 
     this.renderComments(); 
    } 
}); 

var CommentsListView = Backbone.View.extend({ 
    renderCommentView: function(comment) { 
     // Create a new CommentView 
     var commentView = new CommentView({ 
      model : comment 
     }); 
     // Append it to the comments ul that is part 
     // of the view 
     this.$el.append(commentView.el); 
     commentView.render(); 
    }, 
    render: function() { 
     var thisView = this; 
     // Iterate over each Comment Model 
     _.each(this.collection.models, function (comment) { 
      // Call the renderCommentView method 
      thisView.renderCommentView(comment); 
     }); 
    } 
}); 


var CommentView = Backbone.View.extend({ 
    tagName: "li", 
    className: "comment", 
    template: _.template($("#comment-template").html()), 
    render: function() { 
     this.$el.empty(); 
     this.$el.append(this.template(this.model.toJSON())); 
    } 
}); 

// Create a posts collection 
var posts = new Posts(postsObject, {parse: true}); 

// Pass it to the PostsListView 
var postsListView = new PostsListView({ 
    collection: posts 
}); 
// Render the view 
postsListView.render(); 

는 JSON 객체에서 읽는 여러 컬렉션의 좋은 사용을 가지고 있습니다.

내가 가지고있는 것은 내가 읽어야 할 JSON 파일이며, 결국 업데이트를 위해 쓰는 것입니다.

누군가가 바이올린을 통해 컬렉션의 인라인 JSON 객체에서 데이터를 읽는 대신 JSON 파일에서 데이터를 읽는 방법을 이해할 수 있습니까? jQuery의 아약스 방법과 PHP를 사용하여

감사

답변

0

일반 예 :

클라이언트 측 :

$.getJSON("http://www.example.com/document.json", function (data) { 
    data.someProperty = "new value"; 
    saveFile(data); 
}); 

function saveFile(json) { 
    $.post("http://www.example.com/save-file-api.php", {data: json}, function (data) { 
    console.log(data); 
    }); 
} 

서버 측 (저장 파일-api.php) :

<?php 
    if ($_POST["data"]) { 
    if (file_put_contents("/document.json", $_POST["data"]) !== false) { 
     echo "File saved successfully."; 
    } else { 
     echo "Error while saving file."; 
    } 
    } 

이것은 여러 가지 방법으로 수행 될 수 있습니다. 기본적으로 JSON 문서를 요청하고 그 문서를 서버로 보내면 저장됩니다.

백본에도 an API for this이 포함되어 있으므로 조사하고 싶지만 외관상으로는 jQuery를 사용합니다.

+0

안녕하세요, 잭슨 감사합니다.하지만 그건 내가 찾고있는 것이 아닙니다. 나는 내가하고있는 일 (PHP 아님)의 범위에서 파일에 쓰고 jQuery를 사용하여 읽는 방법을 안다. JSON을 파일에서 backbone.js 컬렉션으로 가져 와서 템플릿의 뷰를 통해 출력하는 방법을 마친 후 인라인 개체입니다. – thenexus00

+0

'Collection.url','Collection.fetch()'및'Collection.sync()'를 확인하십시오. 그 사람들은 유망 해 보입니다. – Jackson