捕获事件,创建将模型添加到现有集合主干木偶的所有视图

时间:2015-07-20 13:04:48

标签: javascript backbone.js marionette

我已实现以下功能:

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'app',
    'views/y/x/FlightScheduleLayoutView',
    'collections/y/x/ScheduleCollection'
], function($, _, Backbone, Marionette, App, FlightScheduleLayout, ScheduleCollection) {
    var FlightScheduleListView = Backbone.Marionette.CollectionView.extend({
        collection: ScheduleCollection,
        itemView: FlightScheduleLayout,
        doSort: function(sortCode, sortDirection) {
            this.collection.setSortField(sortCode, sortDirection);
            this.collection.sort();
            this.collection.trigger('reset');
        },
        onAfterItemAdded: function(itemView) {
            if ($(itemView.el).hasClass("flight")) {
                var flight = $(itemView.el);
                var flightDetailsBtn = flight.find(".flight_details");
                var flightDetails = flight.find(".option_details");
                var count = parseInt(this.children.length);
                var flightDetailsId = "flight-details-" + count;
                flightDetailsBtn.attr("data-target", "#" + flightDetailsId);
                flightDetails.attr("id", flightDetailsId);
                flight.find("[data-toggle=tooltip]").tooltip();
            }
        }
    });
    return FlightScheduleListView;
});

现在js中的某个功能可以执行以下操作:

this.flightScheduleListView = new FlightScheduleListView({ collection: schedules });

稍后在代码中添加这种情况:

this.flightScheduleListView.collection.add(this.flightSchedules.models.slice(this.numberOfFlightSchedulesVisibleCurrently, this.numberOfFlightSchedulesVisibleCurrently + this.flightSchedulesPerPage));

使用OnAfterItemAdded完美无缺。但这是耗时的,因为它遍历每个视图。当我们向视图集合添加内容时,是否有任何渲染函数被调用?我不能使用OnRender,因为它只在View实例化时调用,而不是在添加到集合时调用。

1 个答案:

答案 0 :(得分:0)

onAddChild回调

此回调函数可让您了解子视图的时间 实例已添加到集合视图中。它提供访问 已添加的子项的视图实例。

Marionette.CollectionView.extend({
  onAddChild: function(childView){
    // work with the childView instance, here
  }
});

参考文献: http://marionettejs.com/docs/v2.4.1/marionette.collectionview.html#onaddchild-callback