Mike Barlow - BarDev Mike Barlow - BarDev - 1 year ago 63
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).

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

<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();

var loginView = new LoginView();

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

I create jsFiddle example so that there could be a working example for other to look at.

Answer Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download