Backbone视图在bootbox中的'this'上下文

时间:2015-06-16 21:12:10

标签: javascript backbone.js underscore.js marionette

我试图在bootbox模式中创建我的新对象。 如何在bootbox回调中访问this.collection? 在我看来_bind会很有用,但我不知道怎么做。

以下内容发生在Marionette.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')
},

1 个答案:

答案 0 :(得分:2)

我通常会这样做,创建一个新变量(通常是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');
}

希望这有帮助