主干视图在引导框中的“这个”上下文

Backbone view's 'this' context in bootbox

本文关键字:这个 上下文 视图      更新时间:2023-09-26

我正在尝试在引导盒模态中创建新对象。如何在引导盒回调中访问 this.collection?在我看来,_bind会很有用,但我不知道怎么做。

以下情况发生在木偶.compositeView 中

create: function(evt) {
    console.log('create');
    evt.preventDefault();
    var modal = bootbox.dialog({
        title: "Nueva Seccion",
        message: Module.Templates['documents/create/course/chapter/chapterModal'],
        buttons: {
            success: {
                label: "Guardar",
                className: "btn-success",
                callback: function() {
                    var chapterNo = $('#chapterNo').val();
                    var chapterDesc = $('#chapterDesc').val();
                    var chapter = new Module.Models.Chapter({
                        chapterNo: chapterNo,
                        chapterDesc: chapterDesc,
                    });
                    var sub = new Module.Models.subChapter({});
                    chapter.get('subChapters').add(sub)
                    this.collection.add(chapter);
                }
            }
        }
    });
    modal.modal('show')
},

我通常会做这个技巧,创建一个保存正确此值的新变量(通常是 self),如下所示:

    create: function(evt) {
    var self = this;
    console.log('create');
    evt.preventDefault();
    var modal = bootbox.dialog({
        title: "Nueva Seccion",
        message:  Module.Templates['documents/create/course/chapter/chapterModal'],
        buttons: {
            success: {
                label: "Guardar",
                className: "btn-success",
                callback: function () {
                    alert(self.collection);
                    var chapterNo = $('#chapterNo').val();
                    var chapterDesc = $('#chapterDesc').val();
                    var chapter = new Module.Models.Chapter({
                        chapterNo: chapterNo,
                        chapterDesc :chapterDesc,
                    });
                    var sub = new Module.Models.subChapter({});
                    chapter.get('subChapters').add(sub)
                    self.collection.add(chapter);
                }
            } 
        }
    });
    modal.modal('show');
}

希望这有帮助