3

I'm trying to call loadPhotos, but I get an error saying that loadPhotos is not defined. I tried this.loadPhotos(); but then I get an error saying that the object doesn't have such a method. I'm pretty new at this and still trying to figure out what has access to what and such, and I'd greatly appreciate if someone could point me in the right direction. What am I doing wrong?

Here's my code:

    Album = Backbone.Collection.extend ({
    model: Photo,
    url: "/api/",
    albumName: "",
    initialize: function(models, options){
        options || (options = {});
        if (options.title) {
            this.albumName = options.title;
        };

        $.ajax({
            type: "GET",
            url: this.url,
            data: "album=" + this.albumName,
            dataType: "json",
            success: function(data){
                console.log(data);
                loadPhotos(data); // <<< the problem is right here
            },
            error: function(jqXHR, textStatus, errorThrown){
                console.log("FETCH FAILED: " + errorThrown);
            }
        });

    },

    loadPhotos: function(filenames){
        for (var i = 0; i < filenames.length; i++ ){

            var photo = new Photo( {fileurl: filenames[i] });
            var photoView = new PhotoView( { model: photo} );
            this.add(photo);

        }


    }


});
4

2 回答 2

4

如果您showPhotos直接调用它将具有全局上下文(即window)。

如果您只是传递对它的引用,this.showPhotos那么它也不会起作用,因为这不会确定this在随后调用它时将其用作上下文。

要解决这个问题,您还需要让 jQuery 设置正确的值this,这可以通过以下context选项来完成:

$.ajax({
   ...,
   context: this,
   success: this.loadPhotos,
   error: ...
});

如果您的成功除了 call什么都不loadPhotos做,设置context变量允许您直接传递对该函数的引用(如上所示),而不是在另一个函数体中包装对它的调用。

于 2013-05-04T17:26:13.940 回答
4

您误解了thisJavaScript 中的作用域和工作方式。

像这样调用函数

loadPhotos(data);

将查找loadPhotos在从成功回调到全局范围的各种范围内调用的函数,但不存在此类函数,因为该函数已附加到您的集合实例。

this.loadPhotos(data)

更接近,但它完全取决于this引用的内容。this是 JavaScript 中的一个特殊关键字,它指向的对象取决于函数的调用方式。在您的情况下this,完全取决于 jQuery 的行为。您想使用对集合的引用。通用名称,以便更容易知道该变量引用的对象是selfthat有时_this

this一种方法是保存对引用集合的外部指向的对象的引用。如果将其保存到变量中,它将正常工作。

initialize: function(models, options){
    // Stuff

    var self = this;

    $.ajax({
        type: "GET",
        url: this.url,
        data: "album=" + this.albumName,
        dataType: "json",
        success: function(data){
            console.log(data);

            // Call the function on the collection.
            self.loadPhotos(data);

        },
        error: function(jqXHR, textStatus, errorThrown){
            console.log("FETCH FAILED: " + errorThrown);
        }
    });

},

另一种选择是按照@alnitak 的回答说,并使用该context属性显式传递正确的回调上下文。

于 2013-05-04T17:24:26.610 回答