我正在使用backbone.js(AMD)和jquery mobile。我有问题在视图页面上显示数据。有时候html页面运行不正常。我可以做些什么来解决我的问题?任何解决方案?
courseModel
define(['underscore', 'backbone'], function(_, Backbone) {
var courseModel = Backbone.Model.extend({
});
return courseModel;
});
courseCollection
define(['underscore', 'backbone', 'model/course/courseModel'], function(_, Backbone, courseModel) {
var courseCollection = Backbone.Collection.extend({
model: courseModel,
url: "http://localhost:8888/impec-api/member/get_all_courses.php",
parse: function(data) {
return data.tbl_courses;
}
});
return courseCollection;
});
view.js
define(['jquery', 'underscore', 'backbone','model/course/courseCollection', 'text!modules/course/courseViewTemplate.html'], function($, _, Backbone, courseCollection,courseViewTemplate) {
var CourseView = Backbone.View.extend({
//initialize template
template:_.template(courseViewTemplate),
initialize: function() {
this.$el.off();
if (localStorage.studentId == null) {
window.location.replace("#login");
}
},
//render the content into div of view
render: function() {
var that = this;
this.collection = new courseCollection();
this.collection.fetch({
success: function(collection, response) {
that.$el.append(that.template({courses:that.collection.models}));
return that;
},
error: function(collection, response) {
alert("error");
}
});
return this;
}
});
return CourseView;
});
HTML
<div data-role="header">
<a href="#main">Back</a>
<h1>Course</h1>
</div>
<div data-role="content" >
<ul data-role="listview">
<% _.each(courses, function(course) { %>
<li><%= course.get('name') %></li>
<% }); %>
</ul>
</div>
输出
提前多多感谢。
答案 0 :(得分:0)
define(['jquery', 'underscore', 'backbone','model/course/courseCollection', 'text!modules/course/courseViewTemplate.html'], function($, _, Backbone, courseCollection,courseViewTemplate) {
var CourseView = Backbone.View.extend({
//initialize template
template:_.template(courseViewTemplate),
initialize: function() {
this.$el.off();
if (localStorage.studentId == null) {
window.location.replace("#login");
}
},
//render the content into div of view
render: function() {
var that = this;
this.collection = new courseCollection();
this.collection.fetch({
success: function(collection, response) {
var container = document.createDocumentFragment();
_.each(collection, function(subview) {
container.appendChild(subview.render().el)
});
that.$el.append(that.template(container));
}
});
return this;
}
});
return CourseView;
});
我认为你的模板中不需要更多的_.each ...回流会好很多