Search code examples
javascriptbackbone.jsmodel-view-controllermarionettebackbone-views

Backbone - Access a View's $el.attr outside of the ItemView


I have the following ItemView (there is no model associated with the view, it's a very basic "form" which has a submit or cancel and a single input field):

App.BasicForm = Backbone.Marionette.ItemView.extend({
    template: "build/templates/basic-form.html",
    tagName: "div",
    attributes: {
        id: "some-id",
        style: "display: none;"
    },

    events: {
        "click button#bf-submit": "bfSubmit",
        "click button#bf-close": "bfClose"
    },

    bfSubmit: function() {
        var bfInputField= document.getElementById('bfSomeData').value;
    },

    bfClose: function() {
        this.$el.hide();
    }

});

So by default, this view is hidden (but is instantiated when App starts).

I want to have a button which, when clicked, simply changes the attribute style display to block.

I can do this easily like this:

document.getElementById('bfBasicFormDiv').style.display = "block";

However, I'd rather call the view's $el.attr and edit it there, something along the lines of:

App.BasicForm.$el.attr({style: "display: block;"});

However, this returns an undefined, and I can see no way of retrieving the attribute of the View (it's easy with models using .get()) but that doesn't hold for a view.

Thank you for any advice.

Gary


Solution

  • App.BasicForm is not an instance, so it doesn't hold an element. You need to initialize it and you will be able to reference the element with $el:

    var basicForm = new App.BasicForm({
        el: document.getElementById('bfBasicFormDiv')
    });
    basicForm.$el.css({display: "block"});