Mike Barlow - BarDev Mike Barlow - BarDev - 5 months ago 8
jQuery Question

In Backbone.js using jQuery, what is the correct way to select an element within a view?

In the code below I have two jQuery selectors that seem to work correctly. Is there a reason to do one instead of the other, or is there another preferred way?

var val1 = $("#username", this.el ).val()
var val2 = $(this.el).find("#username").val();


I'm aware that there should not be multiple elements with the same id, but if there are multiple elements with the same id, what is the best way to select only the element in the view (see example below for username).

<body>
Username: <input type="text" id="username" /><br />
<br /><br />
<div id="login">
Username: <input type="text" id="username" /><br />
<button id="loginButton">Login</button>
</div>

<script type="text/javascript">
var LoginView = Backbone.View.extend({
el: "#login",
events: {
"click #loginButton": "login"
},

login: function () {
var val1 = $("#username", this.el ).val()
var val2 = $(this.el).find("#username").val();

console.log(val1);
console.log(val2);
}
})
var loginView = new LoginView();
</script>
</body>


--------------------- Update ------------------------

I create jsFiddle example so that there could be a working example for other to look at.
http://jsfiddle.net/BarDev/9QpKy/

Answer

For brevity, I usually use the Backbone-provided shortcut:

this.$('#username')

which is an alias for $('#username', this.el);

However, any selection method you use will work well enough. The other two ways that you've got in your example are good.

Comments