0

How can i access to this.today inside of the Moved function? It will be called via jQuery so the this keyword will be overwritten by jQuery to jQuery object or a DOM element.

Here is something similar to what I have:

(function(Map) {
    Map.Timeline = {
        today: null,

        Init: function () {
            jQuery("#timeline").mousemove(Map.Timeline.Moved); // or this.Moved
        },

        Moved: function (event) {
            console.log(this);                  // jQuery Object or DOM element
            console.log(this.today);            // fails
            console.log(Map.Timeline.today);    // works fine
        },

        // more code here ...
2
  • You mean this = Map.Timeline Commented Apr 21, 2013 at 10:08
  • @jacktheripper yes, you mean I manually rewrite it? Commented Apr 21, 2013 at 10:09

2 Answers 2

7

Use jQuery.proxy() to use a custom context in a callback call

jQuery('#timeline').mousemove(jQuery.proxy(Map.Timeline.Moved, this));
Sign up to request clarification or add additional context in comments.

1 Comment

+1 finally a nice example on where to use that feared proxy ;)
1

You can store this before it is overwritten:

(function(Map) {
var myvar = $(this);
Map.Timeline = {
    today: null,


    Init: function () {
        jQuery("#timeline").mousemove(Map.Timeline.Moved); // or this.Moved
    },

    Moved: function (event) {
        console.log(myvar);                  // jQuery Object or DOM element
        console.log(myvar.today);            // fails
        console.log(Map.Timeline.today);    // works fine
    },

    // more code here ...

2 Comments

Your code does not work. You can't var myvar in an object like that.
Actually I don't wanted to store the jQuery this ... I wanted to prevent the overwritten of the native this keyword. What you doing there is to storing the jQuery object ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.