1

I'm trying to use something like this:

var a = Marionette.Object.extend({
    initialize: function () {
        //Works fine
        this.listenTo(this, "something", function(){...});

        //Problem
        (function(){
            this.listenTo(this, "somethingElse", function(){...});
        })();

        //Same...
        var b = function(){
            this.listenTo(this, "somethingElse", function(){...});
        }

        b();
    }
});

When I try to run this code, it says:

Cannot read property 'listenTo' of undefined

for the functions. But the question is why?

As far as I know, the initialization: get's called, when everything is ready, that's why the other listener at the beginning works. If I put the listener into a function, it should be the same, because, when it gets called, the Object is already initialized so this is present.

Any idea how could I solve this with, leaving the listener inside the function?

Thanks in advance!

Solution for the above (thanks to sp00m)

-- New question --

Achieving the same within an object:

var a = Marionette.Object.extend({
    b: (function(){
        this.listenTo(this, "somethingElse", function(){...});
    })()
});
Dave
  • 49
  • 8
  • http://stackoverflow.com/a/962040/1225328 – sp00m Nov 26 '15 at 16:02
  • What do you mean? At the beginning of the `initialize` function, add `var self = this;`. Then, in the nested functions, use `self` everywhere you used `this`: `self.listenTo(self, "somethingElse", function(){...});`. – sp00m Nov 26 '15 at 16:23
  • Is there any way to achieve the same result within an object? If I take the same code as above, but put the self invoking function into a property, than how could I provide `this` inside? – Dave Nov 26 '15 at 16:41
  • Could you provide this code in your question? – sp00m Nov 26 '15 at 16:43
  • This is a weird usecase, since `b` will be `undefined`... Anyway, have you actually tried with `this` in this case? Because I believe that it should work as is... – sp00m Nov 26 '15 at 16:55
  • Yes, I tried. It says the same (Cannot read property 'listenTo' of undefined). – Dave Nov 26 '15 at 17:01

2 Answers2

1

You could use the var self = this idiom:

var a = Marionette.Object.extend({
  initialize: function () {

    var self = this; // maintain a reference to initialize's this

    (function(){
        self.listenTo(self, "somethingElse", function(){...});
    })();

  }
});

More details: What underlies this JavaScript idiom: var self = this?

Community
  • 1
  • 1
sp00m
  • 44,266
  • 23
  • 127
  • 230
0

Pass this to your function with .bind(this):

var a = Marionette.Object.extend({
    b: (function(){
        this.listenTo(this, "somethingElse", function(){...});
    }.bind(this)()
});

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

misantronic
  • 992
  • 1
  • 9
  • 20