Reputation: 15
i just dont know how to call a another polymer function in a ajax success.
This is my code:
<script>
(function () {
// these variables are shared by all instances of app-globals
var firstName = "John";
function setData(data) {
firstName = data;
console.log("Data gesetzt:" + firstName);
}
Polymer({
ready: function () {
this.setTest("Example"); //Works
$.ajax({
async: false,
type: "GET",
url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from,
dataType: 'jsonp',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
this.setTest(); //Doesnt work
}
});
},
setTest: function () {
console.log("hi");
}
});
})();
</script>
Thats the console log from the success function: Uncaught TypeError: undefined is not a function.
So how can i call the setTest: function(){} in my callback?
Upvotes: 1
Views: 1069
Reputation: 707326
You need to set the context option for the jQuery ajax call so that this
in the success handler has the right value (it will normally point to the jqXHR object):
Polymer({
ready: function () {
this.setTest("Example"); //Works
$.ajax({
// set the context option so this will have the desired value
// in the success handler
context: this,
async: false,
type: "GET",
url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from,
dataType: 'jsonp',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
this.setTest(); // should work now
}
});
},
setTest: function () {
console.log("hi");
}
Or alternately, you could save the this
value like this into another variable that can then be used from the callbacks:
Polymer({
ready: function () {
// save this value into another variable so it can be used in callbacks
var self = this;
this.setTest("Example"); //Works
$.ajax({
async: false,
type: "GET",
url: "http://www.jsv-lippstadt.de/?json=get_category_posts&slug=" + this.from,
dataType: 'jsonp',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
self.setTest(); // should work now
}
});
},
setTest: function () {
console.log("hi");
}
Upvotes: 4