2

我正在开发我的第一个 RequireJS/Backbone 应用程序,但我碰壁了。这里有很多代码气味,我知道我只是缺少模式。

我有一条显示所有促销的路线,还有一条显示特定促销的路线(按 ID):

showPromotions: function () {
    var promotionsView = new PromotionsView();
},
editPromotion: function (promotionId) {
    vent.trigger('promotion:show', promotionId);
}

在我的促销视图初始化程序中,我更新了我的 PromotionsCollection & fetch。我还订阅了集合上的重置事件。这调用 addAll 最终构建所有 Promotions 的 ul 并将其附加到 DOM 中的容器 div 中。

define([
  'jquery',
  'underscore',
  'backbone',
  'app/vent',
  'models/promotion/PromotionModel',
  'views/promotions/Promotion',
  'collections/promotions/PromotionsCollection',
  'text!templates/promotions/promotionsListTemplate.html',
  'views/promotions/Edit'
], function ($, _, Backbone, vent, PromotionModel, PromotionView, PromotionsCollection, promotionsListTemplate, PromotionEditView) {
    var Promotions = Backbone.View.extend({
        //el: ".main",
        tagName: 'ul',
        initialize: function () {
            this.collection = new PromotionsCollection();
            this.collection.on('reset', this.addAll, this);
            this.collection.fetch();
        },

        render: function () {
            $("#page").html(promotionsListTemplate);
            return this;
        },
        addAll: function () {
            //$("#page").html(promotionsListTemplate);
            this.$el.empty().append('<li class="hide hero-unit NoCampaignsFound"><p>No campaigns found</p></li>');
            this.collection.each(this.addOne, this);
            this.render();
            $("div.promotionsList").append(this.$el);
        },

        addOne: function (promotion) {
            var promotionView = new PromotionView({ model: promotion });
            this.$el.append(promotionView.render().el);
        }    
    });
    return Promotions;
});

列表中的每个促销都有一个带有 href 的编辑按钮#promotion/edit/{id}。如果我先导航到列表页面,然后单击编辑,它就可以正常工作。但是,我无法直接导航到编辑页面。我知道这是因为我在视图的初始化方法中填充了我的集合。我可以有一个“if collection.length == 0, fetch”类型的调用,但我更喜欢不需要执行这种检查的设计。我的问题:

  1. 无论我走哪条路线,我如何确保我的收藏被填充?
  2. 我在我的addAll方法中调用 render 来拉入我的模板。我当然可以将该代码移入addAll,但总体而言,该代码也有异味。我是否应该有一个负责呈现模板本身并根据需要实例化我的列表/编辑视图的“父视图”?

谢谢!

4

1 回答 1

2

这是一个例子。请记住,有不止一种方法可以做到这一点。事实上,这可能不是最好的,但我自己这样做,所以也许其他人可以帮助我们俩!

首先,您在这个 js 文件中有很多导入。如果您像这样导入它们,随着时间的推移添加/删除它们会更容易管理:

define(function( require ){
  // requirejs - too many includes to pass in the array
  var $ = require('jquery'),
      _ = require('underscore'),
      Backbone = require('backbone'),
      Ns = require('namespace'),
      Auth = require('views/auth/Auth'),
      SideNav = require('views/sidenav/SideNav'),
      CustomerModel = require('models/customer/customer');
      // blah blah blah...});

不过,这只是一个风格建议,您的电话。至于收款业务,是这样的:

  Forms.CustomerEdit = Backbone.View.extend({

    template: _.template( CustomerEditTemplate ),

    initialize: function( config ){
      var view = this;
      view.model.on('change',view.render,view);
    },

    deferredRender: function ( ) {
      var view = this;
      // needsRefresh decides if this model needs to be fetched.
      // implement on the model itself when you extend from the backbone
      // base model.
      if ( view.model.needsRefresh() ) {
        view.model.fetch();
      } else {
        view.render();        
      }
    },

    render:function () {
      var view = this;
      view.$el.html( view.template({rows:view.model.toJSON()}) );
      return this;
    }

  });


   CustomerEdit = Backbone.View.extend({

    tagName: "div",

    attributes: {"id":"customerEdit",
                 "data-role":"page"},

    template: _.template( CustomerEditTemplate, {} ),


    initialize: function( config ){
      var view = this;
      // config._id is passed in from the router, as you have done, aka promotionId
      view._id = config._id;

      // build basic dom structure
      view.$el.append( view.template );

      view._id = config._id;
      // Customer.Foo.Bar would be an initialized collection that this view has
      // access to.  In this case, it might be a global or even a "private" 
      // object that is available in a closure 
      view.model = ( Customer.Foo.Bar ) ? Customer.Foo.Bar.get(view._id) : new CustomerModel({_id:view._id});

      view.subViews = {sidenav:new Views.SideNav({parent:view}),
                       auth:new Views.Auth(),
                       editCustomer: new Forms.CustomerEdit({parent:view,
                                      el:view.$('#editCustomer'),
                                      model:view.model})
                                    };

    },

    render:function () {
      var view = this;
      // render stuff as usual
      view.$('div[data-role="sidetray"]').html( view.subViews.sidenav.render().el );
      view.$('#security').html( view.subViews.auth.render().el );
      // magic here. this subview will return quickly or fetch and return later
      // either way, since you passed it an 'el' during init, it will update the dom
      // independent of this (parent) view render call.
      view.subViews.editCustomer.deferredRender();

      return this;
    }

同样,这只是一种方式,可能是非常错误的,但我就是这样做的,而且效果很好。我通常在 dom 中放置一条“加载”消息,子视图最终会用替换 html 呈现。

于 2012-12-08T00:24:43.287 回答