【问题标题】:how to render multiple views with their models from ajax calls in backbone如何通过主干中的 ajax 调用使用模型渲染多个视图
【发布时间】:2015-09-23 06:22:26
【问题描述】:

大家好,我正在尝试在主干中绘制具有多个模型和相关视图的屏幕。为此,我对服务器进行了响应式 ajax 调用,以获取此 vie 的数据。首先我认为解决方案可能是 jquery 函数 $when(ajaxcall1,ajaxcall2)done(function) ,但是 ....

Model1.js

getFById: function (id, context, success, error) {
    this.fetch({
        data: {
            id: id
        }
    }).success(function () {
        success();
    }).error(function () {
        error();
    });
},

解析函数数据

parse: function (response) {
    response.pedidosEntrega = new App.PedidosbookingCollection(response.datosPedidosbookingDto);
    response.cabeceraBookingDto = response.cabeceraBookingDto;
    return response;
}

model2.js

getFByBooking: function (idBooking, context) {
    return $.ajax({
        async: true,
        context: context,
        cache: false,
        type: 'GET',
        dataType: 'json',
        contentType: 'application/json',
        data: {
            id: idBooking
        },
        url: this.datosPorFUrl,
    });
},

在我的 router.js 中有渲染视图的调用。

$.when(this.model.getFById(idBooking, idFactura, this),
       this.collectionF1Candidatas.getFByBooking(idBooking))
    .done(_.bind(function (modelBooking, facturasCandidatas) {
        this.asociarF1BookingExito(facturasCandidatas);
    }, this));

问题是模型 1 中的函数解析与这个多次调用是异步的,并且不会在 $when 语句中执行。如何使用 parse 函数对 ajax 调用进行 sincronyze?

我知道这不是骨干网的最佳解决方案。有人可以告诉我在这种技术中实现它的更好解决方案吗?

谢谢大家。。。

【问题讨论】:

    标签: javascript jquery ajax backbone.js asynchronous


    【解决方案1】:

    首先,将成功(和错误?)回调传递给getFByBooking 函数,以将接口与模型的getFById 函数对齐。这样,您可以以相同的方式对待它们:

    getFByBooking : function(idBooking, context, success /*, error*/) {
        $.ajax({
            // ...
            success: success
        });
    }
    

    现在,在您的路由器中,您可以将相同的成功回调传递给它们,但不要在第一个响应时调用它。您可以在这里利用下划线/lodash 的_.after 的力量:

    var success = _.bind(function (modelBooking, facturasCandidatas) {
        this.asociarF1BookingExito(facturasCandidatas);
    }, this);
    
    // let's tell it to only be invoked on the second call
    success = _.after(success, 2);
    
    this.model.getFById(idBooking, idFactura, success /*, error*/);
    this.collectionF1Candidatas.getFByBooking(idBooking, idFactura, success /*, error*/);
    

    我不知道 ECMA 6 是否在您的客户端上可用,但如果是这样,您也可以使用 generators 来完成同样的事情,更优雅。这是一个video,它清楚地表明了这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      相关资源
      最近更新 更多