我正在尝试使用backbone.js显示项目列表。基本上,backbone应该能够将项目.fetch()到项目集合中。这是可行的,我可以从充满项目的异步请求中看出这一点。
但是,如何在页面加载时呈现它们呢?关于使用“bootstrapped”的reset()方法的文档并不多。如有任何帮助,我们不胜感激!谢谢。
app.js:
var oldSync = Backbone.sync;
Backbone.sync = function(method, model, success, error){
var newSuccess = function(resp, status, xhr){
if(xhr.statusText === "CREATED"){
var location = xhr.getResponseHeader('Location');
return $.ajax({
url: location,
success: success
});
}
return success(resp);
};
return oldSync(method, model, newSuccess, error);
};
(function($) {
window.Project = Backbone.Model.extend({});
window.Projects = Backbone.Collection.extend({
model: Project,
url: PROJECT_ENDPOINT,
parse: function(data) {
return data.objects;
}
});
window.ProjectView = Backbone.View.extend({
tagName: 'li' ,
className: 'project',
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.projects = new Projects();
this.projects.fetch(function(data) {
console.log("haha");
});
this.template = _.template($('#project-template').html());
},
render: function() {
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
})(jQuery);模板:
.........
<script>
PROJECT_ENDPOINT = "{% url api_dispatch_list resource_name="project" %}";
</script>
<script type="text/template" charset="utf-8" id="project-template">
<span class="project-title"><%= title %></span>
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>发布于 2011-09-08 15:50:02
您可以将引导模型添加到模板中:
<script>
PROJECT_ENDPOINT = "{% url api_dispatch_list resource_name="project" %}";
INITIAL_DATA = <%= collection.to_json %>
</script>然后在视图构造函数中用this.projects.reset(INITIAL_DATA)替换this.projects.fetch(...)
发布于 2011-09-07 23:34:27
我喜欢设置我的应用程序具有某种"start“函数,我使用json数据为预加载的项目调用该函数。
function MyApp(){
this.start = function(initialModels){
var myModels = new MyCollection(initialModels);
var modelsView = new MyModelsView({collection: myModels});
modelsView.render();
// ... other startup code here
}
}html页面有一个脚本博客,看起来像这样:
<script language="javascript">
var myApp = new MyApp();
myApp.start(<%= mymodel.to_json %>)
</script>希望这能有所帮助
https://stackoverflow.com/questions/7336383
复制相似问题