我是新来的主干,我正在练习它再见,通过使用包含数据的json文件做一些博客。一切正常(可能大多数情况下不好的做法可能),但有一件事我想补充。我想在模型更改时更新我的视图。 我想我必须做一个监听器或类似的东西,但我不知道,并尝试了很多不同的东西,我发现在stackoverflow。更新我的模型与骨干更改我的看法
这里是我的代码:
项目(骨干型)
ItemCollection(该骨干网收集)
var ItemCollection = Backbone.Collection.extend({
model: Item,
comparator: function(model) {
if (sortid == "waardering") {
return -model.get(sortid); //sorteert desc
} else {
return model.get(sortid); //sorteert asc
}
}
});
ItemShelfView(该骨干网查看)
var ItemShelfView = Backbone.View.extend({
className: 'itemshelf',
tagName: 'div',
render: function() {
var self = this;
// iterate through each item in the collection
// and add it to the dom
this.collection.each(function(item) {
// create item dom node
var itemEl = $('<div />', {
class: "item well well-lg col-md-5"
});
var itemTitel = $('<h3 />').text(item.get('titel')).attr('class', "col-md-12");
var itemLink = $('<a />').attr('href', '#detail/' + item.get('url_titel')).attr('class', "btn btn-default navigate col-md-12").text('Bekijk het volledige artikel');
var itemAfbeelding = $('<img />').attr('src', item.get('img_path')).attr('class', " thumbnail col-md-4 ");
var artikeltekst = item.get('artikel');
var shortText = jQuery.trim(artikeltekst).substring(0, 200).split(" ").slice(0, -1).join(" ") + "...";
var itemArtikel = $('<p />').text(shortText).attr('class', "col-md-8");
var itemCategorie = $('<span />').text(item.get('categorie')).attr('class', "col-md-8");
var itemWaardering = $('<b class="waardering" />').text(item.get('waardering')).attr('class', "col-md-8");
var itemCommentaar = $('<span />').text(item.get('commentaar')).attr('class', "col-md-8");
// bad practise
itemEl.append(itemTitel);
itemEl.append(itemAfbeelding);
itemEl.append(itemArtikel);
itemEl.append(itemLink);
itemEl.append(itemCommentaar);
itemEl.append(itemCategorie);
itemEl.append(itemWaardering);
// append the fragment to this views root el
self.$el.append(itemEl);
});
return this;
}
});
我的Ajax获得JSON数据
$.ajax({
url: 'api/items.json',
dataType: 'json',
success: function(data) {
console.log(data);
var items = new ItemCollection(data);
var shelf = new ItemShelfView({
collection: items
});
$('#app').append(shelf.render().$el);
// ensure we can edit the items
window.items = items;
window.shelf = shelf;
}
});
谢谢! (我已经看过很多关于计算器的话题。) Grtz!
非常感谢您,本教程非常有用,但你的解释最能帮助我,现在我明白了更多。再次感谢你 :) – Onovar