Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding ID and Class on template dynamically using backbone views

I want to add a ID and CLASS attribute to my view template. this is what i tried but failed.

$("#login").html( _.template( LoginTemplate ) );
        this.loginmodel = new LoginModel();
        this.loginview = new LoginView({
            el: $("#loginContainer"),
            model: this.loginmodel,
            className: "test"
        });

<div id="loginContainer">
    <div id="loginForm">
      <input class="user-input formContainerInput" id="username" placeholder="Username" required="required"/>
      <input class="user-input formContainerInput"  id="password" type="password" placeholder="Password" required="required"/>
      <a class="connection-btn" data-role="button">Connection</a>
      <a class="login-btn" data-role="button">Log In</a>
    </div>

I want to assign id and class using the views and not on the html itself. How will i do it?

update

attemp #1

loginview: function(){
    $("#login").html( _.template( LoginTemplate ) );
    this.loginmodel = new LoginModel();
    this.loginview = new LoginView({
        id: "#loginContainer",
        model: this.loginmodel,
        attributes:{ id:'Test', class: "myClass otherClass" }
    });
},

it even display an error in aptana on the "class" part.

even tried it on the main view since the code above was the parent view.

var LoginView = Backbone.View.extend({
    events: {
        "click .login-btn": "Login",
        "click .connection-btn": 'Connect',
    },
    initialize: function(){
        //some code here
    },
    attributes: {
        id:"test"
    }
});
like image 253
n0minal Avatar asked Dec 20 '22 23:12

n0minal


1 Answers

What about using View.attributes.

You can specify something like:

attributes: {
  id:     "myId",
  class:  "myClass otherClass"
}

I didn't try but maybe you also can use functions to make it even more dynamic:

attributes: {
  id:     function(){ return "element-" + this.id; },
  class:  "myClass otherClass"
}

Beware this only affects to the view.el DOM element.. not any of its children.

Updated

The above solution only works when the View.el is anonymous.

So, the only solution I see can work in your concrete scenario is to manipulate the View.el directly by JavaScript in the initialize() like this:

initialize: function(){
  this.$el.attr( "id", "my-id" );
  this.$el.attr( "class", "myclass1 myclass2" );
},

Check the jsfiddle for three different scenarios manipulating the View.el attributes.

like image 86
fguillen Avatar answered Dec 28 '22 06:12

fguillen