Вопрос

I have a requirejs module that I am defining with no dependancies, which I am porting from an object literal that I used to use. I thought plopping the literal as the return would work, but it loses reference to this. I keep getting the error Cannot call method 'getHeight' of undefined which I am assuming will occur for every instance of this within my object.

Why is it doing so? Because of the scope of return? Here's what I have...

define(function() {
  return {
    // Photos
    photos: {
      // Get photos wrapper
      $photos: function(){
        return $('#photos');
      },
      setHeight: function() {
        var height = this.header.getHeight(); // Here is where I get my first error "Cannot call method 'getHeight' of undefined"
        return this.$photos().height($(window).height() - height);
      },
      setWidth: function() {
        var width = 0;
        $('#photos').find('img').each(function() {
          width += parseInt($(this).width());
        });
        return this.$photos().width(width);
      },
      init: function() {
        this.setHeight();
        this.setWidth();
      }
    },
    // Header
    header: {
      $header: function() {
        return $('header')
      },
      top: function() {
        var self = this;
        return parseInt(self.$header().css('margin-top'));
      },
      bottom: function() {
        var self = this;
        return parseInt(self.$header().css('margin-bottom'));
      },
      getHeight: function() {
        return this.$header().height() + (this.top() + this.bottom());
      }
    },
    // Padd the Body
    padBody: function() {
      var padding = this.header.getHeight();
      return $('.body').css('padding-top', padding);
    },
    loadImages: function() {
      var self = this;

      $("img[data-src]").unveil(200, function() {
        $(this).load(function() {
          $(this).removeClass('loading').addClass('loaded');
          self.photos.init();
        });
      });
    },
    init: function() {
      var self = this;

      // Fire everything
      this.padBody();
      this.loadImages();

      $(window).on('resize', function() {
        self.padBody();
        self.photos.init();
      });
    }
  }
});
Это было полезно?

Решение

In this case 'this' is global object (window or null in strict mode ). You should use constructor ( new ... ) to create your own scope for object functions ( jsbin.com/dubuxonu/1/edit requirejs has no fault )

If you don't want constructor - save scope in variable and use it to call your methods in right context like this

   (function(){
       var moduleObject = {
         meth1: function(){},
         meth2: function(){ moduleObject.meth1() }
       } 
       return moduleObject;
    });

Here i didn't use 'this' and say directly in which object i want to call methods

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top