Handelbars가있는 backbone.js 앱은 다음을 수행합니다.Handlebars.js가있는 Backbone.js에 대한 질문
- 모델, 해당 컬렉션,보기 및 라우터를 설정하십시오.
- 처음에는 서버에서 기사 목록을 가져 와서 Handlebars.js 템플릿을 통해보기를 사용하여 렌더링합니다.
코드는 다음과 같습니다.
(function ($)
{
// model for each article
var Article = Backbone.Model.extend({});
// collection for articles
var ArticleCollection = Backbone.Collection.extend({
model: Article
});
// view for listing articles
var ArticleListView = Backbone.View.extend({
el: $('#main'),
render: function(){
var js = JSON.parse(JSON.stringify(this.model.toJSON()));
var template = Handlebars.compile($("#articles_hb").html());
$(this.el).html(template(js[0]));
return this;
}
});
// main app
var ArticleApp = Backbone.Router.extend({
_index: null,
_articles: null,
// setup routes
routes: {
"" : "index"
},
index: function() {
this._index.render();
},
initialize: function() {
var ws = this;
if(this._index == null) {
$.get('blogs/articles', function(data) {
var rep_data = JSON.parse(data);
ws._articles = new ArticleCollection(rep_data);
ws._index = new ArticleListView({model: ws._articles});
Backbone.history.loadUrl();
});
return this;
}
return this;
}
});
articleApp = new ArticleApp();
})(jQuery);
Handlebars.js 템플릿은
<script id="articles_hb" type="text/x-handlebars-template">
{{#articles}}
{{title}}
{{/articles}}
</script>
위의 코드는 잘 작동하고 기사 제목을 인쇄합니다. Handlebars.js 템플릿에 컨텍스트를 전달할 때, 나는 현재 $(this.el).html(template(js[0]))
를하고있는 중이 야
하지만, 내 질문입니다. 이것이 올바른 방법일까요? js [0] 대신 "js"를 수행하면 JSON 객체의 앞뒤에 대괄호가 있습니다. 따라서 JSON 객체의 배열 객체로 인식합니다. 그래서 나는 js [0]에 가야만했다. 하지만 적절한 해결책이 아닌 것처럼 느껴집니다.
"보기"를 처음 만들 때 아래와 같이 만듭니다.
ws._index = new ArticleListView ({model : ws._articles});
하지만 내 경우에는
, 어떻게해야ws._index = new ArticleListView({collection: ws._articles});
해야하지 I? (나는 튜토리얼 btw를 따르고 있었다). 아니면이게 중요한가요? 나는 둘 다 시도해 보았지만 많은 차이를 만들지는 않았다.
미리 감사드립니다. 당신이 collection
대신 model
의를 사용하여 뷰를 초기화 할 필요가 있도록 콜렉션에 대한 뷰를 작성하는 것처럼
어떻게하면이 handlebar.js 템플릿을 내 – Vinodh