2

What's the difference between jQuery $ and this.$ in Backbone.js View? in a View, I listened to a collection's reset event to empty an element by using below code

//code in View
this.$("#the_id").empty();

however it did not empty my element, then I changed the code to

$("#the_id").empty();

this time it works. so, why this.$ does not do the work?

Shuping
  • 5,388
  • 6
  • 43
  • 66

1 Answers1

2

Calling this.$( selector ) in a view is same as calling $( selector, this ) or $(this).find( selector ).

It gives context for the selector I.E. only elements under this are searched to match the selector whereas normal jQuery $(selector) starts the search from the entire document's root.

Your view should not manipulate elements that it doesn't own, if calling this.$("#the_id").empty(); doesn't do anything it means that the element wasn't under the view's "area of control" or doesn't exist to begin with.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • I used the same event binding to listen to the collections' add event with the handler this.$('#the_id').append(view.render().el) and it works. but why this.$("#the_id").empty() did not work in the collection's reset event handler? – Shuping Nov 07 '12 at 16:41
  • @Shuping are you binding the handler's context to the correct `this` object? – Esailija Nov 07 '12 at 16:42
  • Yes, thanks for your remind, I bond the handler to an incorrect context. your answer resolved my problem! – Shuping Nov 07 '12 at 17:00