我正在使用backboneJS和requireJS以及jQueryMobile。
对于我的所有视图/集合,一切都很好,除了一个集合没有在每个添加上触发渲染方法,只有第一个集合。这是代码:
HTML:
<div data-role="page" id="board">
<div data-role="header">
<h3>My Notes </h3>
</div>
<div data-role="content">
<ul id="listOfNotes" data-role="listview">
</ul>
</div>
</div>
和JavaScript:
var NoteModel = Backbone.Model.extend({
initialize: function(attributes, options)
{
this.set({
"id": attributes["id"] ? attributes["id"] : "",
"label": attributes["label"] ? attributes["label"] : "",
"text": attributes["text"] ? attributes["text"] : "",
"size" : attributes["size"] ? attributes["size"] : ""
});
},
});
var NotesCollection = Backbone.Collection.extend( {
model: NoteModel
});
// Extends Backbone.View
var BoardDetailsView = Backbone.View.extend({
/**
* The View Constructor
* @param el, DOM element of the page
*/
initialize: function(options)
{
this.collection.on("add", this.render, this);
},
render: function() {
this.$el.empty(); // clear the element to make sure you don't double
var self = this; // so you can use this inside the each function
this.collection.each(function(noteModel){
console.log('render note : ' + noteModel);
var id = noteModel.get("id");
var text = noteModel.get("text");
var li = "<li><a href=\"#note/"+id+"\">"+text+"</a></li>";
self.$el.append(li);
});
self.$el.listview().listview("refresh", true);
return this;
},
/**
* clear the view manually
*/
empty: function() {
this.$el.empty();
}
});
var note1 = new NoteModel({'noteId':'1', 'text':'label 1'});
var note2 = new NoteModel({'noteId':'2', 'text':'label 2'});
var note3 = new NoteModel({'noteId':'3', 'text':'label 3'});
window.app.boardDetailsView = new BoardDetailsView({el: '#listOfNotes', collection: new NotesCollection()});
window.app.boardDetailsView.collection.add(note1);
window.app.boardDetailsView.collection.add(note2);
window.app.boardDetailsView.collection.add(note3);
答案 0 :(得分:0)
问题在于,所有笔记都被分配了相同的ID(实际上是一个空白字符串,这本身可能不是一个好主意),因为您正在检查 id 属性但是传入 noteId 属性。
var NoteModel = Backbone.Model.extend({
initialize: function(attributes, options)
{
this.set({
"id": attributes["noteId"] ? attributes["noteId"] : "",
"label": attributes["label"] ? attributes["label"] : "",
"text": attributes["text"] ? attributes["text"] : "",
"size" : attributes["size"] ? attributes["size"] : ""
});
}
});
以下是指向jsbin
的链接