1

i have the following javascript object:

var Playlist = function(callback) {
    $.ajax({
        url:'/playlist'
    })
    .done(function(data) {
        this.html = data;
        callback({},this);
    })
    .fail(function(err) {
        callback(err,{});
    });
};

for this object, i declared a prototype method:

Playlist.prototype = {
    render : function() {
        $('#main').html(this.html);
    }
};

now, when i create a new object und try to call the 'render' function like this

function renderPlaylist() {
    var playlist = new Playlist(function(err, obj) {
        obj.render();
    });
}

renderPlaylist();

i get a 'undefined is not a function'. it seems not to know the render function, which i declared in the prototype. what am i missing here? thanks for help.

Hinrich
  • 11,828
  • 4
  • 37
  • 54
  • 4
    `callback({},this);` the `this` is not what you think. See [JavaScript “this” keyword](http://stackoverflow.com/questions/3127429/javascript-this-keyword), [MDN `this` documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) and [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Volune Sep 06 '14 at 12:30
  • thank you, you are totally right. i changed my constructor. – Hinrich Sep 06 '14 at 12:34

1 Answers1

1

with the help of Volune, i changed my constructor to

var Playlist = function(callback) {
    var playlist = this;
    $.ajax({
        url:'/mpdplaylist'
    })
    .done(function(data) {
        playlist.html = data;
        callback(null,playlist);
    })
    .fail(function(err) {
        callback(err,{});
    });
};

now it works. thank you!!

edit: as Volune pointed out, i replaced the empty object for the error with null in the 'done' callback function

Community
  • 1
  • 1
Hinrich
  • 11,828
  • 4
  • 37
  • 54
  • 1
    If you're using callbacks the same way as NodeJS, you should do `callback(null,playlist);`. This way the callback can more easily check if there were an error. – Volune Sep 06 '14 at 12:52