javascript - 主干渲染 View 未显示...仅在控制台中

标签 javascript backbone.js handlebars.js

我有我的主干路由器:

var AppRouter = Backbone.Router.extend({

    routes:{
        "" : "productos",
    },

    initialize: function(){
        this.productoItem = new Producto();
        //Crear la vista del detalle de un producto

        this.productoItems = new Productos();
        this.productoItems.fetch();

        this.productosView = new ProductsView({collection: this.productoItems});
    },

    productos: function(){
        $('#app').html(this.productosView.render().el);
      //this line seems not to working but putting in a console does the work
    }

});

/*********************************/
var app = new AppRouter();

$(function(){
    Backbone.history.start();
});

这是 View :

var ProductsView = Backbone.View.extend({

    render: function(){
        this.$el.html(Handlebars.templates.products(this.collection));
        return this;
    }
});

最后是我的 Handlebars 模板:

<h1>Y LOS MODELOS SON</h1>
<ul>
{{#each models}}
<li>
{{attributes.familia}}
</li>
{{/each}}
</ul>

所以当我运行这个应用程序时,它只呈现 Y LOS MODELOS SON 这意味着 $('#app').html(this.productosView.render().el);有效,但不完全只有 html 标签...但是当我这样做时:

$('#app').html(app.productosView.render().el)

在控制台中它完美地工作...... 有人可以解释一下我错过了什么吗? 谢谢...

最佳答案

Collection#fetch是一个 AJAX 调用,因此在服务器发回任何内容之前会调用 AppRouter#productos。结果是,当调用 ProductsView#render 时,集合为空,并且模板中的 {{#each models}} 没有任何可迭代的内容。

Collection#fetch 使用 Collection#set将获取的模型合并到集合中。这将触发集合上的“add”“remove”“change”事件。您可以从集合中监听这些事件并重新渲染:

initialize: function() {
    this.listenTo(this.collection, 'add remove change', this.render);
}

但这将非常浪费,因为您将为每个新添加的模型重新渲染 View 。另一种方法是使用 {reset:true} 获取:

When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, in which case the collection will be (efficiently) reset.

reset将触发单个“reset”事件。所以在你的路由器中,你可以说:

this.productoItems = new Productos();
this.productoItems.fetch({ reset: true });

然后在你看来:

initialize: function() {
    this.listenTo(this.collection, 'reset', this.render);
}

使用 {reset: true} 似乎是您的情况下最容易使用的方法。

关于javascript - 主干渲染 View 未显示...仅在控制台中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19485115/

相关文章:

javascript - handlebars #每个数组都是助手

javascript - 如何用react-router替换react组件

javascript - 嵌套 View : binding events with proper ui

javascript - 从多个 View 中使用backbone.js中的常见默认值

javascript - EmberJS + Handlebars : Re-Use rendered views

backbone.js - 查看特定于 Backbone 集合的修改

javascript - 在不更改选项文本的情况下更改下拉选择的文本

javascript - HTML5 Canvas 的 Uncapped 与 SetInterval 帧速率?

javascript - 在 Backbone js View 中分配 ' this' 上下文

javascript - "this.el"在 $ ('ul' , this.el 中的含义)