1

I want to edit my collection using jeditable, where modifyCollection is a function associated with the event dblclick. I have the following code:

initialize : function(options) {
        view.__super__.initialize.apply(this, arguments);
        this.collection = this.options.collection;
        this.render();
    },

render : function() {
        var template = _.template(tpl, {
            collectionForTemplate : this.collection ,
            });
            this.el.html(template);
            return this;
    },

modifyCollection : function (event){
        $('#name').editable(function(value, settings) {
            return (value);
        }
        , 
           { onblur: function(value) {
                this.modelID=event.target.nameID;
                    this.collection = this.options.collection;

                console.log("This Collection is: " + this.collection); //Shows : undefined
                            //  
                            this.reset(value);
                    $(this).html(value); 
                    return (value); 
            }
        });

The idee is to update the model and subsequently, the collection by means of jeditable. The in place editing works fine, but the problem is, I am not able to pass the collection into the function. I want to save all the changes to my collection locally and send them to the server at a later time. What am I doing wrong here?

4

1 に答える 1

1

他の人がこのスレッドを見つけた場合に備えて、コメントを正式な回答に移動しました。

関数のthis内部onblur()はこのコレクションを指していません。関数var self = this;内に追加してから、次のように変更してみてください。modifyCollection()onblur()this.collectionself.collection

modifyCollection : function (event) {

    var self = this;  // Added this line
    // When working with functions within functions, we need
    // to be careful of what this actually points to.

    $('#name').editable(function(value, settings) {
        return (value);
    }, {
    onblur: function(value) {
        // Since modelID and collection are part of the larger Backbone object,
        // we refer to it through the self var we initialized.
        self.modelID = event.target.nameID;
        self.collection = self.options.collection;

        // Self, declared outside of the function refers to the collection
        console.log("This Collection is: " + self.collection);
            self.reset(value);

            // NOTICE: here we use this instead of self...
            $(this).html(value); // this correctly refers to the jQuery element $('#name')
            return (value); 
        }
    });
});

更新-自己に関する予言ノート

@muistooshortは、実際にはwindowのプロパティであることに言及しているため、コードでをself宣言しない場合は、windowobjを参照することになります。var self = this;なぜself存在しているように見えるが機能していないように見えるのかわからない場合は、悪化する可能性があります。

この種のコーディングの一般的な使用法は、の代わりにthatまたはを使用することを好む傾向があります。あなたは警告されました。;-)_thisself

于 2012-09-04T03:17:04.967 に答える