Шаблон underscore.js || связать / добавить позвоночник
Я задал вопрос на днях об этом приложении; после некоторых полезных советов я перешел и теперь думаю, что это другая проблема. Раньше я не получал никакого отображения на экране / никаких ошибок или каких-либо console.logs. После того, как я поработал над этим, у меня теперь есть модель / представление и некоторые функции рендеринга.
Я думаю, что проблема связана с моим шаблоном или с моим приложением. Ниже приведен полный код в его нынешнем виде. Есть // комментарии, где я думаю, что, возможно, есть некоторые проблемы. Любая помощь с этим будет принята с благодарностью.
РЕДАКТИРОВАТЬ:: Спасибо за совет Niranjan. Я сделал некоторые изменения, которые вы упомянули; Я забрал счетчик и образец данных. С этими новыми изменениями мой newsFeed.js больше не читается, и поэтому мне неясно, как заполнить мою коллекцию. Когда я console.log из своей коллекции, я получаю пустой массив с моими показанными по умолчанию значениями, но с файлом json, который не читается в первую очередь, как мне заставить что-либо работать?
РЕДАКТИРОВАТЬ #2:: Еще раз спасибо Ниранджан. С изменениями, которые вы предложили, и несколькими моими, у меня теперь есть код ниже. Проблема, с которой я столкнулся сейчас, заключается в том, что мой массив заполняется слишком много раз. файл JSON имеет всего 8 записей, и из-за моего оператора _.each в моем шаблоне он зацикливается 8 раз, и я хочу, чтобы он зацикливался только один раз, а затем разделял массив на отдельные записи. Я попытался сначала разделить его во время моего анализа ответа, но это не сработало, у вас есть какой-нибудь совет для этого?
под кодом находятся ссылки на живые представления кода и содержимого html / broswer, включая ссылку на файл JSON.
Моя конечная цель - щелкнуть один заголовок и показать соответствующий контент.
(function(){
var NewsFeedModel = Backbone.Model.extend({
defaults: {
title: '',
content: ''
}
});
var NewsFeedCollection = Backbone.Collection.extend({
model: NewsFeedModel,
url : 'newsFeed.js',
parse: function(response) {
console.log('collection and file loaded');
return response.responseData.feed.entries;
}
});
var NewsFeedView = Backbone.View.extend({
el : '.newsContainer ul',
template: _.template($("#feedTemp").html()),
initialize: function(){
var scopeThis = this;
_.bindAll(this, 'render');
this.collection.fetch({
success: function(collection){
scopeThis.render();
}
});
this.collection.bind( 'add', this.render, this);
console.log('View and Template read');
},
render: function () {
this.$el.html(this.template({
feed: this.collection.toJSON()
}));
console.log(this.collection.toJSON());
}
});
var newsFeedCollection = new NewsFeedCollection();
var newsFeedView = new NewsFeedView({
collection: newsFeedCollection
});
var title = newsFeedCollection.find('title');
var content = newsFeedCollection.find('content > title');
$(document).on("click", "#add", function(title, content) {
console.log("I have been clicked");
if($(title) == $(content)){
console.log('they match');
}
else{
console.log('they dont match');
}
$('.hide').slideToggle("slow");
});
}());
Это мой шаблон подчеркивания.
<div class="span12">
<script id="feedTemp" type="text/template">
<% _.each(feed, function(data) { %>
<div id = "titleContent">
<a href='#' id ="add"> <%= data.title %> </a>
<div id="content" class="hide">
<%= data.content %>
</div>
</div>
<% }); %>
</script>
</div>
Я использую Google Drive в качестве испытательного полигона; ссылки на полный HTML / код. https://docs.google.com/file/d/0B0mP2FImEQ6qa3hFTG1YUXpQQm8/edit [кодовый вид] https://googledrive.com/host/0B0mP2FImEQ6qUnFrU3lGcEplb2s/feed.html браузер [View] https://docs.google.com/file/d/0B0mP2FImEQ6qbnBtYnVTWnpheGM/edit [файл JSON]
1 ответ
В вашем коде намного больше вещей, которые можно улучшить. Вот JSFIDDLE.
Пожалуйста, просмотрите комментарии, указанные в коде.
Чтобы попробовать что-то в шаблоне Underscore, проверьте редактор шаблонов Underscore.
Шаблон:
<button id=add>Add</button>
<div class="newsConatiner">
<ul></ul>
</div>
<script id="feedTemp">
<% _.each(feed, function(data) { %>
<div id = "titleContent">
<h2> <%= data.title %> </h2>
<div id="content">
<%= data.content %>
</div>
</div>
<% }); %>
</script>
Код:
(function () {
var NewsFeedModel = Backbone.Model.extend({
//url: 'newsFeed.js',
defaults: {
title: '',
content: ''
}
});
var NewsFeedCollection = Backbone.Collection.extend({
model: NewsFeedModel,
url: 'newsFeed.js',
parse: function (response) {
console.log('collection and file loaded');
return response.responseData.feed.entries;
}
});
var NewsFeedView = Backbone.View.extend({
el: '.newsConatiner',
//template should not be inside initialize
template: _.template($("#feedTemp").html()),
initialize: function () {
_.bindAll(this, 'render');
this.render();
//ADD event on collection
this.collection.bind('add', this.render, this);
console.log('View and Template read');
},
/*
This initialize will fetch collection data from newsFeed.js.
initialize: function () {
var self = this;
_.bindAll(this, 'render');
this.collection.fetch({
success: function(collection){
self.render();
}
});
//ADD event on collection
this.collection.bind('add', this.render, this);
console.log('View and Template read');
},
*/
render: function () {
//This is how you can render
//Checkout how this.collection is used
this.$el.html(this.template({
feed: this.collection.toJSON()
}));
}
});
//Initialized collection with sample data
var newsCounter = 0;
var newsFeedCollection = new NewsFeedCollection([{
title: 'News '+newsCounter++,
content: 'Content'
}]);
//Created view instance and passed collection
//which is then used in render as this.collection
var newsFeedView = new NewsFeedView({
collection: newsFeedCollection
});
$('#add').click(function(){
newsFeedCollection.add(new NewsFeedModel({
title: 'News ' + newsCounter++,
content: 'Content'
}));
});
}());