javascript - Bootbox 中主干 View 的 'this' 上下文

标签 javascript backbone.js underscore.js marionette

我试图在引导框模式内创建新对象。 我如何在 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')
},

最佳答案

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

    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');
}

希望这有帮助

关于javascript - Bootbox 中主干 View 的 'this' 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30878302/

相关文章:

javascript - 如何在不创建滚动条的情况下用 Canvas 元素填充浏览器窗口?

mysql - 配置服务器在本地运行

javascript - 如何理解具有多个参数的函数的组合?

javascript - 在javascript中删除给定字符串的第一个字符的最佳方法

javascript - 如何将每个数组元素插入另一个数组中的每个其他元素?

javascript - puppeteer 师/Node.js : Can I run a script non-stop 24/7?

javascript - Ruby Watir 或 JavaScript : Get 5 first elements of a section

javascript - Backbone.js 集合获取不起作用

javascript - Backbone 集合按多个属性排序

javascript - 以下 Underscore.js 代码如何工作?