将 JQuery 附加到 backbone

Append JQuery with backbone

我正在与 Backbone 和 Dyson 合作模拟 API。我正在尝试显示 JSON 的结果,但出现错误:Uncaught TypeError: self.template is not a function.

ReservaCollectionView = Backbone.View.extend({
initialize: function () {
    if (Session.get('authenticated') && Session.get('authenticated') !== false) {
        this.template = _.template($('#divReservaTpl').html(), {});

        //Vector donde almacenamos las subvistas que corresponden a las reservas
        this.subViewsReservas = [];
        //Instancia de la vista de la paginación
        this.paginacionVista = new PaginacionReservasView({
            collection: this.collection,
            el: '.paginacionReservas',
            reservasPagina: 5,
        });
        //Instancia de la vista del buscador (simulamando los datos del servidor que corresponden a la colección oficinas )
        this.buscadorVista = new BuscadorView({
            el: 'div.buscador-reservas',
            collection: new OficinasCollection(oficinas),
        });
    }
    else {
    }
},
render: function () {
    var self = this;
    //var fragment = document.createDocumentFragment();
    self.$('.contenedor-reservas').empty();
    self.collection.each(function (reserva, index) {
      console.log(reserva);
      console.log(index);

        self.$('.contenedor-reservas').append(self.template({'data': reserva.toJSON()}));

    });

    this.collection.each(function (reserva, index) {
        self.subViewsReservas.push(new ReservaView({
            el: '#' + reserva.get('Idreserva'),
            model: reserva
        }));
    });


    this.collection.each(function (reserva, index) {
        //Limite de la paginacion 5 limite arbitrario
        if (index < 5) {
            //Lo Marcamos como visible y actualiazamos la paginación
            self.collection.get(reserva.get('Idreserva')).set({'Visibilidad': true});
        }
    });

    this.paginacionVista.render();

    return this;
},

});

珍藏价值JSON():

{"Idreserva":"1","Idcliente":403,"Idtarifa":3,"Idgrupo":3,"Bono":"WG5000218E","BonoAgencia":"7741124","Fecha":"2015-02-17 11:49:09","Dropoffdate":"2015-02-17 11:49:09","Pickupdate":"2015-02-17 11:49:09","Grupo":"XXX","reserva_status":3,"Estado":3,"status":true}

可能发生这种情况的一种情况是条件

if (Session.get('authenticated') && Session.get('authenticated') !== false) 

失败。

在这种情况下,this.template = _.template($('#divReservaTpl').html(), {}); 不会执行并且 template 属性 不会出现在视图中。

我建议按照文档中的建议在视图定义本身中包含 template 属性:

ReservaCollectionView = Backbone.View.extend({
 initialize: function () 
 },
 template: _.template($('#divReservaTpl').html()),
 render: function(){}
});

然后您可以根据条件安全地选择是否render查看。

另一种可能发生此错误的情况是,执行 render 方法的上下文 (this) 引用视图以外的其他内容。

我认为当您执行

时,您正在失去上下文
var self = this;

尝试将下面的代码放在初始化函数中。

如果您在初始化时执行 var self = this 将引用对象视图,但如果您在函数中执行它,它将引用该函数!