Search code examples
backbone.jsbackbone-views

How do I specify the name of the button element


I would like to have a button with the name 'fire', but even though I specified the value, the name doesn't show up, just an empty button. Please help.

 var Tweets = Backbone.View.extend({
        tagName: 'button',
        id: 'tweets',
        className: 'btn btn-primary',
        value: 'fire',
        initialize: function() {
        },
        render: function() {     
            return this;
        }

Solution

  • Use the "attributes" property of the view, which allows you to specify a hash of name+value pairs. They will get included as attributes on the generated DOM element (that is, the "button" in your case).

    Add this to your Tweets declaration:

    ...
    attributes: { "name": "fire" },
    ...
    

    That would cause the generated button element to look like this:

    <button name="fire" id="tweets" class="btn btn-primary" value="fire"></button>
    

    Relevant documentation is here: http://backbonejs.org/#View-attributes

    Note, however, that while you asked how to specify the "name", that might not be what you were really trying to do. If your goal is to get a button element with the text "fire" displayed on the button itself, you need to set the content of the button tag, rather than some attribute of the tag.

    Relevant documentation for the button element is here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

    To do that, you'll need to update your render method to manually set the generated "button" element's content. Something like this should work for the render method:

    render: function() {
        this.$el.text("fire");
        return this;
    }
    

    That should cause the generated button element to look like this:

    <button id="tweets" class="btn btn-primary" value="fire">fire</button>