【问题标题】:Javascript module parttern ajaxJavascript 模块模式 ajax
【发布时间】:2016-07-08 01:14:01
【问题描述】:

我正在学习 javascript 设计模式。因此,我将粗略的 jquery 代码转换为更清晰的模块模式。问题是,在 ajax 以模块模式(对象文字)加载后,我将如何调用单击事件。我曾经使用 $(document).ajaxcomplete(callback) 来解决它。

这里是工作的 supergetti 代码

$('.meidaBtn, #media_load_btn').on('click', function(event) {
  event.preventDefault();
  $('.media').show(500);

  $('#mediaBox').html('Loading...');
  var link = location.origin + '/dashboard/media';

  $.ajax({
    url: link
  }).done(function(data) { // data what is sent back by the php page
    $('#mediaBox').html(data); // display data

    // Click through
    $('.imageBox img').bind('click', function() {
      var src = $(this).attr('src');
      var alt = $(this).attr('alt');
      src = src.replace('tumbnail_', '');

      tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
      $('.media').hide();
    });
  });

});

这里是 javascript 模块模式/对象字面量

var mediaPlugin = {
  init: function() {
    this.cacheDom();
    this.bindEvents();
  },

  // Cache Dom 
  cacheDom: function() {
    this.baseUrl = location.origin + '/dashboard/media';

    this.$button = $('.meidaBtn, #media_load_btn');
    this.$media = $('.media');
    this.$mediaBox = $('#mediaBox');
    this.$imageBox = $('.imageBox img');
  },

  // Bind Events
  bindEvents: function() {
    this.$button.on('click', this.render.bind(this));
    this.$imageBox.on('click', this.addImage.bind(this));
  },

  // Show Data
  render: function(e) {
    e.preventDefault();
    this.$media.show(500);
    this.loadData();
  },

  // Load the data
  loadData: function() {
    var that = this;
    $.ajax({
      url: this.baseUrl,
      type: 'GET',
      success: function(data) {
        // console.log(that.$mediaBox);
        that.$mediaBox.html(data);
      },
      error: function() {
        console.log("An error occored!");
      },
      complete: function() {
        // console.log("I am now complete");
        // that.loadMore();
      }
    });
  },

  // Add Image
  addImage: function() {
    var src = $(this).attr('src');
    var alt = $(this).attr('alt');
    src = src.replace('tumbnail_', '');

    tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
    this.$media.hide();
  }
};

mediaPlugin.init();

【问题讨论】:

    标签: javascript jquery html ajax design-patterns


    【解决方案1】:

    下面提供的方法为对象添加了一个简单的属性,用作委托/回调。您只需将您的函数指向它,然后它会自动调用,因为它是在完整事件中调用的。

    var mediaPlugin = {
      init: function() {
        this.cacheDom();
        this.bindEvents();
      },
    
      // Cache Dom 
      cacheDom: function() {
        this.baseUrl = location.origin + '/dashboard/media';
    
        this.$button = $('.meidaBtn, #media_load_btn');
        this.$media = $('.media');
        this.$mediaBox = $('#mediaBox');
        this.$imageBox = $('.imageBox img');
      },
    
      // Bind Events
      bindEvents: function() {
        this.$button.on('click', this.render.bind(this));
        this.$imageBox.on('click', this.addImage.bind(this));
      },
    
      // Show Data
      render: function(e) {
        e.preventDefault();
        this.$media.show(500);
        this.loadData();
      },
    
      loadDataComplete: function() {},
      
      // Load the data
      loadData: function() {
        var that = this;
        $.ajax({
          url: this.baseUrl,
          type: 'GET',
          success: function(data) {
            // console.log(that.$mediaBox);
            that.$mediaBox.html(data);
          },
          error: function() {
            console.log("An error occored!");
          },
          complete: function() {
            // console.log("I am now complete");
            // that.loadMore();
            that.loadDataComplete();
          }
        });
      },
      
      // Add Image
      addImage: function() {
        var src = $(this).attr('src');
        var alt = $(this).attr('alt');
        src = src.replace('tumbnail_', '');
    
        tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
        this.$media.hide();
      }
    };
    
    var myCompleteFunction = function myCompleteFunction() {}
    mediaPlugin.init();
    mediaPlugin.loadDataComplete = myCompleteFunction;
    mediaPlugin.loadData();
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案2】:

      我终于想出了如何让这段代码工作。我使用了 jquery .delegate(),现在我像魔术一样工作。下面是工作代码。感谢@abc123 的光临。

      var media = (function(){
      // Cache dom
      var baseUrl = location.origin+'/dashboard/media';
      
      var $button = $('.meidaBtn, #media_load_btn');
      var $media = $('.media');
      var $mediaBox = $('#mediaBox');
      var $imageBox = $mediaBox.find('img');
      
      var options = { 
          url: baseUrl,
          type: 'GET',
          success: function(data){
              $mediaBox.html(data); 
          },
          error: function(){
              console.log("An error occored!");
          },
          complete: function(){
              // console.log("I am now complete");
              // that.loadMore();
          }
      };
      
      // Bind Events
      $button.on('click', _render);
      $mediaBox.delegate('.imageBox', 'click', _addImage);
      
      function _render(e){
          e.preventDefault();
          $media.show(500);
          _loadData();
      }
      
      // Load images
      function _loadData(){
          $.ajax(options);
      }
      
      // Add Images 
      function _addImage(){
          img = $(this).find('img');
      
          console.log(img.attr('src')); // This should display the image url
      }
      

      })();

      【讨论】:

      • 很高兴您找到了解决方案,但请注意 delegate() 已弃用。请改用on()(除非您出于某种原因必须使用旧版本的 jQuery。)
      • 我一直在尝试 .on() 但直到我尝试了 .delegate() 后它才起作用。我仍然会尝试使 .on() 工作。感谢您抽出宝贵时间@MattBrowne
      • @MattBrowne 终于使用了 .on() 并且成功了。我想当它不起作用时,我正在以一种扭曲的方式实现它。我终于查阅了jquery手册。再次感谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 2012-04-25
      • 2011-07-02
      • 2012-12-19
      • 2012-12-09
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多