Backbone view's 'this' context in bootbox

205 views Asked by At

I am trying to make the creation of my new object happen inside a bootbox modal. How can i access this.collection inside the bootbox callback? it seems to me that _bind would be useful, but i dont know how.

the following happens inside a 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

There are 1 answers

2
wezzy On BEST ANSWER

I usually do this trick, create a new variable (usually self) that hold the correct this value, something like 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');
}

Hope this helps