请问如何每 10 秒更新一次视图?或者只有在我的 json 文件中发生更改时才重新渲染或重新获取此视图?
我的主要 js:
var AppRouter = Backbone.Router.extend({
routes: {
"" : "categories",
},
initialize: function () {
this.headerView = new HeaderView();
$('.header').html(this.headerView.el);
},
categories: function () {
if (!this.CategoriesView) {
this.CategoriesView = new CategoriesView();
}
$('#content').html(this.CategoriesView.el);
this.headerView.selectMenuItem('categories-menu');
},
utils.loadTemplate(['HeaderView'], function() {
app = new AppRouter();
Backbone.history.start();
});
我的收藏 :
var Categories = Backbone.Collection.extend({
url: 'api/categories_and_products.json'
});
JSON:
[
{
"title": "Pizza",
"id": 1,
"products": [{ "name" : "Romana"},{"name" : "Viennese"},{"name" : "Capricciosa"},{"name" : "Quattro formaggi"},{"name" : "Bianca"},{"name" : "Alla casalinga"}]
},
{
"title": "Pasta",
"id": 2,
"products": [{ "name" : "Spagetti Napolitana"},{"name" : "Penne Arrabiata"},{"name" : "Tagliatelle with cream sauce"},{"name" : "Tortellini"}]
}
]
我的类别 HTML 模板:
<script type="text/template" id="categories-template">
<% _.each(categories, function(category) { %>
<li class="categorycls"><%= category.get('title') %></li>
<% _.each(category.get("products"), function(product) { %>
<li class="productscls">
<%= product.name %>
</li>
<% }); %>
<% }); %>
</script>
这是我想一直更新的观点:
var CategoriesView = Backbone.View.extend({
initialize:function () {
this.render(this);
this.loop();
},
loop:function(){
setInterval(function() { this.render() }, 1000)
},
render:function (that) {
var categories = new Categories();
categories.fetch({
success: function (categories) {
var template = _.template($('#categories-template').html(), {categories: categories.models});
that.$el.html(template);
}
})
}
});
我不知道如何重新渲染或重新获取...我需要更新来自 json 的新数据,而无需手动刷新网站...
现在控制台中每 10 秒出现一次错误:
Uncaught TypeError: Object [object global] has no method 'render'