2013-04-22 6 views
0

는 임 새로운 백본으로, 게시물을 통해 반복 할 때 템플릿으로 워드 프레스 JSON 플러그인에서 JSON을 가져 오기 및 렌더링을 시도하지만, 나는 다음과 같은 오류 catch되지 않은 ReferenceError가 얻을 : 게시물은 정의되지 않은 어떤 도움에 감사드립니다 . 감사합니다 ...Backbone.js catch되지 않은 오류 ReferenceError는

jQuery(function($) { 
    var Post = Backbone.Model.extend(); 
    var Posts = Backbone.Collection.extend({ 
     model: Post, 
     url: '/api/get_post/?json=get_recent_posts', 
     parse: function(resp) { 
      console.log("posts", resp); 
      return resp; 
     } 
    }); 
    var listView = Backbone.View.extend({ 
     el: '#content', 
     template: _.template($("#post-template").html()), 
     initialize: function() { 
      this.model.bind("reset", this.render, this); 
     }, 
     render: function() { 
      $(this.el).html(this.template(this.model.toJSON())); 
      return this; 
     } 
    }); 
    var AppRouter = Backbone.Router.extend({ 
     routes: { 
      "!/archive": "archive" 
     }, 
     archive: function() { 
      this.postList = new Posts(); 
      this.postListView = new listView({ 
       model: this.postList 
      }); 
      this.postList.fetch(); 
      this.postListView.render(); 
     } 
    }); 
    var app = new AppRouter(); 
    Backbone.history.start(); 
}); 

템플릿

<script id="post-template" type="text/template"> 
    <ul> 
     <% _.each(posts, function(post) { %> 
     <li id="<%= post.id %>"> 
      <a href="<%= post.url %>"><%= post.thumbnail %></a> 
     </li> 
     <% }); %> 
    </ul> 
</script> 

JSON

{ 
    "status": "ok", 
    "count": 1, 
    "count_total": 1, 
    "pages": 1, 
    "posts": [{ 
     "id": 4, 
     "type": "post", 
     "slug": "test-post", 
     "url": "http:\/\/localhost:8888\/2013\/04\/test-post\/", 
     "status": "publish", 
     "title": "Test Post", 
     "title_plain": "Test Post", 
     "content": "", 
     "excerpt": "", 
     "date": "2013-04-17 15:12:21", 
     "modified": "2013-04-19 14:13:00", 
     "categories": [], 
     "tags": [], 
     "author": { 
      "id": 1, 
      "slug": "admin", 
      "name": "admin", 
      "first_name": "", 
      "last_name": "", 
      "nickname": "admin", 
      "url": "", 
      "description": "" 
     }, 
     "comments": [], 
     "comment_count": 0, 
     "comment_status": "closed", 
     "thumbnail": "http:\/\/localhost:8888\/wp-content\/uploads\/2013\/04\/test-image-150x150.jpg" 
    }] 
} 
+0

해당 오류는 템플릿 컴파일러에서 발생합니다. 힌트로'render()'에서'console.log (this.model.toJSON())'을 실행하고 어떤 것이 출력되는지보십시오. 또한,'this.postList'는 콜렉션입니다. 그래서 왜 그것을'model'으로 전달합니까? – Bojangles

+0

마지막 부분에 대해 @Bojangles, 백본의보기에'collection' 키가 없으므로 "콜렉션 뷰"를 만들고 싶다면 여전히'model' 키를 사용해야합니다. 그것은별로 문제가되지 않습니다. – Loamhoof

+0

@Loamhoof 의견을 말하기 전에 [documentation] (http://backbonejs.org/#View-constructor)를 읽으십시오. Backbone docs에서 :'전달 된 경우 모델, 컬렉션, 엘, 아이디, 클래스 이름, tagName 및 속성과 같은 뷰에 직접 연결되는 몇 가지 특별한 옵션이 있습니다. ' – Bojangles

답변

1

Collection#toJSON를 호출하면 배열을 반환합니다. 따라서 posts 키가 없습니다. $(this.el).html(this.template(this.model.toJSON()[0]));을 사용하여 컬렉션에 단 하나의 모델 만 있습니다 (이상한 경우). 당신은 resp.posts을 반환 할 parse 방법에있는 당신의 응답을 구문 분석 할 수 있습니다

그래서 컬렉션 더 많은 의미를 가지고 있으며, 실제로 포스트 당 하나 개의 Post 모델을 생성합니다.

$(this.el).html({ 
    posts : this.template(this.model.toJSON()) 
}); 

대신 : 당신이 당신의 밑줄 템플릿 컬렉션/배열을 포함하는 변수로 posts을 사용하려면

$(this.el).html(this.template(this.model.toJSON())); 
0

봅니다 그런 짓을하는 속성으로 템플릿 함수에 전달하십시오.

$(this.el).html(this.template({ posts: this.model.toJSON() })); 

var Posts = Backbone.Collection.extend({ 
    model: Post, 
    url: '/api/get_post/?json=get_recent_posts', 
    parse: function(resp) { 
     console.log("posts", resp); 
     return resp.posts || []; // grab the posts from the JSON 
    } 
}); 

그리고 종종 규칙에 의해 당신이로 전환 할 수 있습니다 : (게시물이 반환되고있는 JSON의 재산으로) 아래와 같은 Posts 컬렉션 클래스는 parse 기능의 게시물을 반환해야 생각했다

this.postListView = new listView({ 
    collection: this.postList 
}); 

을 그리고 템플릿 통화 변경 :보기의 collection 속성을 사용하여 { posts: this.collection.toJSON() }을.

+0

단순히 아니요, 예상 한 결과가 나오지 않습니다. – Loamhoof

관련 문제