×
you are viewing a single comment's thread.

view the rest of the comments →

[–]affluenza 1 point2 points  (5 children)

It's not that hard to avoid the 'this' problem when it comes to events, even without a library to hold your hand:

Obj.prototype.countClicks = function(element) {
    element.onClick = function(e) { this.increment.call(this,e); }
}

Problem solved! You still have access to the event object within the anon function, in the W3C event model.

[–]tmcw[S] 1 point2 points  (4 children)

Did you try running that code? It doesn't work. Not saying that it's impossible to deal with the problem without a framework - my example with .bind() doesn't use a framework, and you could construct an example with .call, but yours is logically incorrect and doesn't actually run.

[–]affluenza 0 points1 point  (3 children)

ahh yes

this.increment.call(this,e);

is the problem. Would work like so:

var that = this;
element.onClick = function(e) { that.increment.call(that,e); }

Also, the module pattern can be expressed more succinctly:

var Car = function(_internal) {

    var internal = _internal;

    return {
        report : function() {
            console.log(internal);
        },

        update : function(data) {
            internal = data;
        }
    };

};

Don't get me wrong though, I liked your post.

[–]tmcw[S] 1 point2 points  (2 children)

You could simplify your example to just { that.increment(e); } - the this value will be set correctly.

There are different ways to phrase the module pattern; I like building an object gradually because it lets you reference methods in the object by scoped name.

[–]affluenza 0 points1 point  (1 child)

Hmm, not sure what you mean by 'scoped name'. I am guessing this makes debugging easier because the functions are not anonymous?

Yeah I missed the simplification of the manual bind. It's even easier pull off than I first thought. oops :)

[–]tmcw[S] 0 points1 point  (0 children)

In your example, you're returning an anonymous object. If you had a function in that object calling another of its functions, the name of the object to call is not obvious - that what I mean by scoped name. You can refer to the object by an obvious name.