【问题标题】:Where do I initialize backgrid in my Backbone/Rails app?在我的 Backbone/Rails 应用程序中,我在哪里初始化 backgrid?
【发布时间】:2013-06-24 19:49:01
【问题描述】:

我有一个 Backbone.js 应用程序并正在尝试与 Backgrid 集成,但我无法理解我应该在哪里调用 new Backgrid。我尝试在事物渲染后在我的视图中调用它,但附加网格不起作用,因为事物尚未实际上渲染。这是一些代码:

SpreadsheetIndex.js.coffee

D3.Views.SpreadsheetsIndex = Support.CompositeView.extend
  initialize: (options) ->
    this.tables = options.tables
    this.resources = options.resources
    _.bindAll(this, 'render')

  render: ->
    this.renderTemplate()
    this.renderSpreadsheets()

    resources = this.resources

    this.tables.each (table) ->

      subset = resources.subcollection
        filter: (resource) -> 
          resource.escape('table_id') == table.escape('id')

      grid = new Backgrid.Grid
        columns: table.attributes.columns
        collection: subset

      $("#"+table.escape('id')).append(grid.render().$el);
    return this

  renderTemplate: ->
    this.$el.html(JST['spreadsheets/index']({ spreadsheets: this.tables }))

  renderSpreadsheets: ->
    self = this
    self.$('tbody').empty();

电子表格/index.jst.ejs

<% spreadsheets.each(function(spreadsheet) { %>
  <h4><%= spreadsheet.escape('name')%></h4>
  <div id='<%= spreadsheet.escape('id') %>'></div>
<% }) %>

问题是$("#"+table.escape('id')) 选择器没有选择任何东西,因为模板还没有呈现。感觉就像我把它放在了错误的地方。我做错了什么?

【问题讨论】:

    标签: ruby-on-rails backbone.js coffeescript backgrid


    【解决方案1】:

    我猜你想使用视图的@$ 方法而不是$ 将选择器本地化到视图的el

    this.tables.each (table) =>
      #...
      @$("#"+table.escape('id')).append(grid.render().$el);
    

    请注意,-&gt; 已变为 =&gt;(以获取正确的 @/this),它现在使用 @$ 而不是 $


    当我在这里的时候,你可以做一些其他的事情来让你的代码更符合思想:

    1. class D3.Views.SpreadsheetsIndex extends Support.CompositeView 而不是 JavaScripty D3.Views.SpreadsheetsIndex = Support.CompositeView.extend
    2. 使用@ 而不是this,例如@tables = options.table 而不是this.tables = options.table
    3. 如果你认为+更简洁,你可以使用字符串插值代替:

      @$("##{table.escape('id')}")
      
    4. 您很少需要bindAll,而不是_.bindAll(this, 'render'),您可以将render 定义为render: =&gt; 以使绑定自动发生。

    5. 在 CoffeeScript 中你很少需要 var self = this 技巧,你通常可以使用 =&gt; 来代替。而且你不需要任何一个:

      renderSpreadsheets: ->
        self = this
        self.$('tbody').empty();
      

      你可以renderSpreadsheets: -&gt; @$('tbody').empty()

    【讨论】:

    • @chapmand:我添加了一些您可能感兴趣的其他指针。
    • 太棒了。感谢您的提示。我对 Coffeescript 和 Backbone 还很陌生,所以这很有帮助。
    猜你喜欢
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2011-12-03
    • 2016-03-26
    • 2021-01-29
    相关资源
    最近更新 更多