beNerd
beNerd

Reputation: 3374

Unable to access DOM elements of template in backbone View

I have a view like this:

var InvoiceForm = Backbone.View.extend({
    template: _.template(addform),
    initialize: function () {
        this.$("#buyer").val("test");
    }
});

I have the template addform containing the buyer id element. This isn't setting the value. I know i am doing something stupid here :)

Upvotes: 1

Views: 1057

Answers (2)

IanO.S.
IanO.S.

Reputation: 1382

If you are trying to do this on a click event - to change to the 'test' value, you could do it with the following

initialize: function(){
            this.model.on('change', this.render, this);         
        },

    render: function() {
            this.$el.html( this.template(this.model.toJSON()) );
            this.input = this.$('#buyer');
            return this;
        },

    events: {
     'click #buyer' : 'editValue',
    },

    editValue: function(){
        this.input.val("test");
    }

Upvotes: 1

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

Backbone templates in Views aren't automatically rendered. In fact in the Backbone documentation, there are some examples how you could do that.

If you use templates in your view, which should be rendered on initialize you can write your code like this :

var InvoiceForm = Backbone.View.extend({
    template: _.template(addform),
    render: function() {
        this.$el.html(this.template());
        return this;
    },
    initialize: function () {
        this.render(); // Rendering your template in your this.el element
        this.$("#buyer").val("test"); // Setting the value of #buyer in your template
    }
});

You can later use this view like this:

var form = new InvoiceForm({ el: $("#wrapper_for_invoiceform") });

Check the demo in this fiddle : http://jsfiddle.net/hsn7J/

Upvotes: 2

Related Questions