为什么在获取集合之后的el是未定义的

时间:2013-07-08 03:43:07

标签: jquery backbone.js requirejs backbone-views backbone-events

我有这个视图(ordersView),它在初始化时获取订单,并在完成重新呈现视图后。 el属性是在实例化所述视图时定义的,因此在路由器中定义。我在实例化之后调用了渲染并显示了#order el,但是在fetch el之后是未定义的,为什么会这样?

console logs notice logs on line 36

我的 ordersView.js 视图:

// Menu View
// =============

// Includes file dependencies
define([ "jquery",
         'underscore',
         "backbone",
         'handlebars',
         "collections/menu",
         "collections/orders",
         "collections/stores",
         'hbs!template/ordersTemplate',
], function( $, _, Backbone, Handlbars, MenuCollection, OrdersCollection, StoresCollection, OrdersTemplate ) {

    // Extends Backbone.View
    var OrdersView = Backbone.View.extend( {


        // The View Constructor
        initialize: function() {

            OrdersCollection.fetch({'success': this.render})

        },

        events: {
        },        

        showMoreInfo: function(e) {
            $(e.target).closest('.store').toggleClass('hideinfo');
        },

        // Renders all of the Category models on the UI
        render: function() {
            console.log('rendered');
            console.log( this.$el );
            this.$el.html( OrdersCollection.toJSON() );

        }


    } );

    // Returns the View class
    return OrdersView;

} );

这是我的 router.js 文件:

// Filename: router.js
define([
  'jquery',
  'underscore',
  'backbone',
  '../views/ordersView',
], function($, _, Backbone, OrdersView) {

  var AppRouter = Backbone.Router.extend({
    routes: {
      // Default
      '*actions': 'defaultAction'
    }
  });

  var initialize = function(){

    var app_router = new AppRouter;

    app_router.on('route:defaultAction', function (actions) {
        var ordersView = new OrdersView({ el: $("#orders") });
        ordersView.render();
    });

    Backbone.history.start();
  };
  return { 
    initialize: initialize
  };
});

我正在使用JQuery jquery-1.10.2,Backbone.js backbone-amd 1.0.0和RequireJS AMD loader

1 个答案:

答案 0 :(得分:3)

尝试将执行上下文绑定到render(),然后再将其填充到.fetch()

OrdersCollection.fetch({'success': _.bind(this.render, this)})