$.widget( "app.serverTime", {
_create: function () {
$.get("/timestamp.php", function( data ) {
this.timestamp = data.timestamp;
})
},
getTime:function() {
return this.timestamp;
}
});
$(".clock").serverTime();
$(".clock").serverTime("getTime")
I have the above jQuery UI Widget when I call the getTime I am getting in the value I am expected but instead I am getting the jQuery Selector, when i set the value manually without using Ajax it works as expected.
I think the issue is because of this. Inside the get function this not refer to the plugin calee object.
So save this
reference and use it later like:
$.widget( "app.serverTime", {
_create: function () {
var _this=this;
$.get("/timestamp.php", function( data ) {
_this.timestamp = data.timestamp;
})
},
getTime:function() {
return this.timestamp;
}
});
Consider that the $.get
is async, so the timestamp property will be set when the $.get
finish, but the code runs.
Concept:
$(".clock").serverTime();
setTimeout(function () {
console.log($(".clock").serverTime("getTime"));
}, 5000);
So think about handle the async properly.
Just a small addition to @Irvin's answer: You can use $.proxy
to easily change this
within the function, and this is especially useful for working with the widget factory;
Additionally you should have a default value for the timestamp
variable -- and should include an underscore in front of it's name (as that's the convention for "private" (pseudoprivate) fields -- I assume it's supposed to be private as you have a getter):
$.widget( "app.serverTime", {
_create: function () {
$.get("/timestamp.php", $.proxy(function( data ) {
this._timestamp = data.timestamp;
}, this))
},
_timestamp: "Tue Jul 15 2014 08:50:38 GMT+0100 (GMT Standard Time)",
getTime:function() {
return this._timestamp;
}
});