1

How can I access the values of "runit" and "property2"?

$("#selector").draggable({
    property1: "myvalue",
    property2: "myvalue",
    property3: "myvalue",
    start: function() {
        var runit = 'one value';
    },
    stop: function(){                       
        //Access Value of runit
        //Acess Value of property2
    }
});

3 Answers 3

4

You can't access runit from stop() as it is scoped only to the start() method. You should be able to access property2 with

this.property2

You could add runit to the object's properties, eg

{
    property1: "myvalue",
    property2: "myvalue",
    property3: "myvalue",
    runit:     null,
    start: function() {
        this.runit = 'one value';
    },
    stop: function(){
        console.log(this.runit);
        console.log(this.property2);
    }
}

A possibly working example - http://jsfiddle.net/9rZJH/

Sign up to request clarification or add additional context in comments.

10 Comments

you can access runit if you declare it without var. Then it would be global.
@bhamlin Cheers, I've clarified my answer
While you should be able to access the object’s scope inside the start and stop methods, it is not a safe assumption. It depends on how they are called internally.
This answer is inaccurate; the thisBinding is (almost) purely dependant on how the method is called, and your solution certainly doesn't guarantee the appropriate binding in the general case, nor in the specific case of jQueryUI's draggable event handlers.
I find that particular jQuery habit rather helpful, and not nasty at all. In any case, I would be glad to elaborate: var obj = {foo:42, bar:function(){ alert(this.foo); }}, fn = obj.bar; fn(); You should be expecting an alert of 42, notice that that fails and I haven't used .call().
|
2

In order to access runit you need to define it outside the object’s scope:

var runit;

$("#selector").draggable({
    property1: "myvalue",
    property2: "myvalue",
    property3: "myvalue",
    start: function() {
        runit = 'one value';
    },
    stop: function(){                       
        //Access Value of runit
        console.log(runit);
        //Acess Value of property2
        console.log(this.property2);
    }
});

property2 should be accessible via this.property2 but that depends on how the stop method is called internally.

1 Comment

Did you mean "object's scope" because there's no such thing (in js) as object scope.
1

Another option is to just return runit. I mean, it all depends on what you want to accomplish:

start: function() {
    var runit = 'one value';
    // Stuff
    return { runit: runit };
},
method: function(){
    var foo = this.start().runit;
}

Comments

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.