6

对于有几年 Web 开发经验的人来说,这是一个有点菜鸟的问题,但是在Programmer Stack ExchangeGoogle都没有找到答案后,我决定在这里问它。

我正在为Node.js使用Express Web 框架,但这个问题并不特定于任何 Web 框架或编程语言。

这是从数据库中查询的游戏列表。每个游戏实体都是一个表行,使用for 循环生成:

    table.table
      tbody
        for game in games
          tr
            td.span2
              img.img-polaroid(src='/img/games/#{game.largeImage}')   
              // continues further  

在此处输入图像描述

每个Rating块,以及每个Buy按钮/模态对话框都是由 for 循环生成的,其 id 与游戏匹配。例如,刺客信条的购买按钮将具有id="price-assassins-creed"#{variable} - 是您在 Jade 中引用从服务器传入的变量的方式。

button.btn.btn-primary.btn-mini(id='price-#{game.slug}', href='#buyModal', role='button', data-toggle='modal')

.modal.hide.fade(id='modal-#{game.slug}', tabindex='-1', role='dialog', aria-labelledby='myModalLabel', aria-hidden='true')
            .modal-header
              span.lead Game Checkout
                img.pull-right(src='/img/new_visa_medium.gif')
            .modal-body
              label
                i.icon-user
                |  Name on Card
              input.input-medium(type='text')
              label
                i.icon-barcode
                |  Card Number
              input.input-medium(type='text', placeholder='•••• •••• •••• ••••', maxlength=16)

              label
                i.icon-time
                |  Expiration Date
              input.input-mini(type='text', placeholder='MMYY', maxlength=4)
              label
                i.icon-qrcode
                |  Card Code
              input.input-mini(type='text', placeholder='CVC', maxlength=4)
            .modal-footer
              button.btn(data-dismiss='modal', aria-hidden='true') Cancel
              button.btn.btn-primary(id='#{game.slug}') Buy

script(type='text/javascript')
  $('#_#{game.slug}').raty({
    path: '/img',
    round : { down: .25, full: .6, up: .76 },
    score: #{game.rating}/#{game.votes},
    readOnly: true
  });

将其乘以游戏数量,这就是我在一页上有多少内联脚本。

更糟糕的是,我必须考虑以下情况:

  • 用户未登录:以只读模式显示以上评分脚本。
  • 用户已登录,但尚未投票

...在这种情况下,请使用以下脚本:

script(type='text/javascript')
                    $('#_#{game.slug}').raty({
                      path: '/img',
                      round : { down: .25, full: .6, up: .76 },
                      score: #{game.rating}/#{game.votes},
                      readOnly: false,
                      click: function (score, event) {
                        var self = this;
                        $.meow({
                          message: 'Thanks for voting. Your rating has been recorded.',
                          icon: 'http://png-3.findicons.com/files/icons/1577/danish_royalty_free/32/smiley.png'
                        });
                        $.ajax({
                          type: 'POST',
                          url: '/games/rating',
                          data: {
                            slug: $(self).attr('id').slice(1),
                            rating: score
                          },
                          success: function () {
                            console.log('setting to read-only');
                            $(self).raty('readOnly', true);
                          }
                        });
                      }
                    });
  • 用户已登录但未评级:复制并粘贴此特定if-else条件的另一个只读脚本。

长话短说,试图在我的.jade模板文件中维护所有这些 JavaScript 已成为维护的噩梦,而且我的标记看起来脏得令人无法接受。

有什么解决方案?这似乎是 CRUD 应用程序的常见场景。理想情况下,我想将所有 javascript 移动到单独的.js文件中。但是,如果我可以删除一些重复的代码,那也很棒。

问题是如果我将内联 javascript 移动到单独的文件中,我怎么知道我在评价哪个游戏?我如何知道用户点击了哪个购买按钮?

现在没有歧义,因为对于N个游戏,我有 N 个购买按钮、N个模态对话框和N个评分脚本。不管任何人如何看待这种编程风格,它都是一种糟糕的代码维护方式。

请与菜鸟分享一些见解!

先感谢您。

这是我的 games.jade 文件的完整代码片段:

extends layout

block content
  br
  ul.nav.nav-pills
    if heading === 'Top 25'
      li.active
        a(href='/games') Top 25
    else
      li
        a(href='/games') Top 25

    if heading === 'Action'
      li.active
        a(href='/games/genre/action') Action
    else
      li
        a(href='/games/genre/action') Action

    if heading === 'Adventure'
      li.active
        a(href='/games/genre/adventure') Adventure
    else
      li
        a(href='/games/genre/adventure') Adventure

    if heading === 'Driving'
      li.active
        a(href='/games/genre/driving') Driving
    else
      li
        a(href='/games/genre/driving') Driving

    if heading === 'Puzzle'
      li.active
        a(href='/games/genre/puzzle') Puzzle
    else
      li
        a(href='/games/genre/puzzle') Puzzle

    if heading === 'Role-Playing'
      li.active
        a(href='/games/genre/role-playing') Role-Playing
    else
      li
        a(href='/games/genre/role-playing') Role-Playing

    if heading === 'Simulation'
      li.active
        a(href='/games/genre/simulation') Simulation
    else
      li
        a(href='/games/genre/simulation') Simulation

    if heading === 'Strategy'
      li.active
        a(href='/games/genre/strategy') Strategy
    else
      li
        a(href='/games/genre/strategy') Strategy

    if heading === 'Sports'
      li.active
        a(href='/games/genre/sports') Sports
    else
      li
        a(href='/games/genre/sports') Sports


  if games.length == 0
    .alert.alert-warning
      | Database query returned no results.
  else
    table.table
      tbody
        for game in games
          .modal.hide.fade(id='modal-#{game.slug}', tabindex='-1', role='dialog', aria-labelledby='myModalLabel', aria-hidden='true')
            .modal-header
              span.lead Game Checkout
                img.pull-right(src='/img/new_visa_medium.gif')
            .modal-body
              label
                i.icon-user
                |  Name on Card
              input.input-medium(type='text')
              label
                i.icon-barcode
                |  Card Number
              input.input-medium(type='text', placeholder='•••• •••• •••• ••••', maxlength=16)

              label
                i.icon-time
                |  Expiration Date
              input.input-mini(type='text', placeholder='MMYY', maxlength=4)
              label
                i.icon-qrcode
                |  Card Code
              input.input-mini(type='text', placeholder='CVC', maxlength=4)
            .modal-footer
              button.btn(data-dismiss='modal', aria-hidden='true') Cancel
              button.btn.btn-primary(id='#{game.slug}') Buy
          tr
            td.span2
              img.img-polaroid(src='/img/games/#{game.largeImage}')
            td
              a(href='/games/#{game.slug}')
                strong
                  = game.title
              |  

              if user.userName
                button.btn.btn-primary.btn-mini(id='price-#{game.slug}', href='#modal-#{game.slug}', role='button', data-toggle='modal')
                  i.icon-shopping-cart.icon-white
                  =  game.price
                if user.purchasedGames && user.purchasedGames.length > 0
                  for mygame in user.purchasedGames
                    if mygame.game.slug == game.slug
                      script(type='text/javascript')
                        $('#price-#{game.slug}').removeAttr('href');
                        $('#price-#{game.slug}').html('<i class="icon-shopping-cart icon-white"></i> Purchased');

              div
                span(id='_' + game.slug)
                span(id='votes', name='votes')
                |  (#{game.votes} votes)
              div
                small.muted
                  div #{game.releaseDate} | #{game.publisher}
                  div #{game.genre}
              p
                =game.description

          // logged-in users
          if user.userName
            if game.votedPeople.length > 0
              for voter in game.votedPeople
                if voter == user.userName || user.suspendedRating
                  script(type='text/javascript')
                    $('#_#{game.slug}').raty({
                      path: '/img',
                      round : { down: .25, full: .6, up: .76 },
                      score: #{game.rating}/#{game.votes},
                      readOnly: true
                    });
                else
                  script(type='text/javascript')
                    $('#_#{game.slug}').raty({
                      path: '/img',
                      round : { down: .25, full: .6, up: .76 },
                      score: #{game.rating}/#{game.votes},
                      readOnly: false,
                      click: function (score, event) {
                        var self = this;
                        $.meow({
                          message: 'Thanks for voting. Your rating has been recorded.',
                          icon: 'http://png-3.findicons.com/files/icons/1577/danish_royalty_free/32/smiley.png'
                        });
                        $.ajax({
                          type: 'POST',
                          url: '/games/rating',
                          data: {
                            slug: $(self).attr('id').slice(1),
                            rating: score
                          },
                          success: function () {
                            console.log('setting to read-only');
                            $(self).raty('readOnly', true);
                          }
                        });
                      }
                    });
            else
              if (user.suspendedRating)
                script(type='text/javascript')
                  $('#_#{game.slug}').raty({
                    path: '/img',
                    round : { down: .25, full: .6, up: .76 },
                    score: #{game.rating}/#{game.votes},
                    readOnly: true
                  });
              else
                script(type='text/javascript')
                  $('#_#{game.slug}').raty({
                        path: '/img/',
                        round : { down: .25, full: .6, up: .76 },
                        score: #{game.rating}/#{game.votes},
                        readOnly: false,
                        click: function (score, event) {
                          var self = this;
                          $.meow({
                            message: 'Thanks for voting. Your rating has been recorded.',
                            icon: 'http://png-3.findicons.com/files/icons/1577/danish_royalty_free/32/smiley.png'
                          });
                          $.ajax({
                            type: 'POST',
                            url: '/games/rating',
                            data: {
                              slug: $(self).attr('id').slice(1),
                              rating: score
                            },
                            success: function () {
                              console.log('setting to read-only');
                              $(self).raty('readOnly', true);
                            }
                          });
                        }
                      });
          else
            script(type='text/javascript')
              $('#_#{game.slug}').raty({
                path: '/img',
                round : { down: .25, full: .6, up: .76 },
                score: #{game.rating}/#{game.votes},
                readOnly: true
              });

          script(type='text/javascript')
            $('##{game.slug}').click(function() {
              var game = this;
              $.ajax({
                type: 'post',
                url: '/buy',
                data:  {
                  slug: $(game).attr('id')
                }
              }).success(function () {
                $('#price-#{game.slug}').attr('disabled', 'true');
                $('#modal-' + $(game).attr('id')).modal('hide');
                humane.log('Your order has been submitted!');
              });
            });
4

1 回答 1

3

读起来太长了。无论如何,我想我明白你在说什么,并会使用这样的格式:

<div id="some_container">
    <!-- The following div would be generated in each iteration of the for loop you speak of -->
    <div class="item-container" data-game-name="Your game name" data-game-id="23">
        <span class="button delete-button">X</span>
    </div>
</div>

而且您的脚本将具有委托(以大大减少绑定的数量):

$(document).ready(function () {
    $("#some_container").on("click", ".delete-button", function () {
        var $this = $(this);
        var $container = $this.closest(".item-container");
        var game_name = $container.data("game-name");
        var game_id = $container.data("game-id");
        // Do whatever with the above 2 variables
    });
});

至于模态的东西,您可以创建一个<div>具有“模板”的“模板”,用于显示什么。然后,当您单击任何按钮时,您使用上述逻辑(获取第一个父.item-container项以获取项目的详细信息,他们用此信息填写模式中的“模板”。然后,“确定”按钮不需要一百万个硬编码的东西 - 只需一个 - 从模板中获取信息并进行任何调用或提交表单。

于 2012-11-27T07:37:36.897 回答