Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a Backbone.View to a 'single' DOM element in a list of similar elements in the DOM

I have the following page structure:

<ul class="listOfPosts">
   <li class="post WCPost" data-postId="1">
      <div class="checkbox"><input type="checkbox" class="wcCheckbox"/></div>
      <div class="PostContainer>
       <!-- some other layout/content here -->
       <ul class="listOfLabels">
          <li class="label"> Label 1</li>
          <li class="label"> Label 2</li>
       </ul>
      </div>
   </li>
   <li class="post WCPost" data-postId="2">...</li>       
   <li class="post WCPost" data-postId="3">...</li>
   <li class="post WCPost" data-postId="4">...</li>
   ...
</ul>

Here is the overly simplistic View:

  var MyView = Backbone.View.extend({
    el:$('.listOfPosts'),

    initialize: function() {
         _.bindAll(this,"postClicked");
    },

    events: {
        "click .wcCheckbox":"postClicked"
    },

    postClicked: function() {
         alert("Got a a click in the backbone!");
        }
  });

Question: I want to know the data Id of post that was clicked. With simple JQuery I can just do the following:

$('.wcCheckbox').live('click' function() {
    alert("Data id of post = "+$(this).parents('.WCPost').data('data-postId'));
}

Now I know that Backbone does event delegation so it needs a DOM reference in the el property. If I give it the .listOfPosts then the event seems to fire perfectly but to get "which" posts were checked I'll have to keep traversing the DOM and pick out the elements that were selected!!! It would be quite expensive in my opinion! How do I do this in Backbone for each individual post?? i.e., How do I bind the view to each individual li.WCPost??

NOTE: I'm not using plain vanilla jQuery since the code that I need to write is best done with Backbone's modular design, but since I'm not a pro with Backbone (yet ;) just a bit confused...

like image 936
PhD Avatar asked Jul 19 '11 17:07

PhD


2 Answers

Using something like $(event.target).data('postId') in your postClicked() function is a normal way to do this kind of stuff, as far as I can tell.

Extensive usage of events might seem unusual at first, but it's a good way to improve code organization, if used properly. You really can get all the data you want from the event in most cases, especially if you have jQuery. (Note that the event passed to your postClicked function is a regular jQuery event object, and everything you can find about it could be applied. Backbone.js uses jQuery's delegate() function to bind events.)

* * *

However, you still can bind events by yourself in the initialize() method of your view.

initialize: function() {
     // Custom binding code:
     this.$('.wcCheckbox').live('click' function() {
         alert("Data id of post = "+$(this).parents('.WCPost').data('data-postId'));
     }
     // No need for this anymore:
     // _.bindAll(this,"postClicked");
},

(this.$(<selector>) is a function that automatically scopes jQuery selectors to your view, equivalent to $(<selector>, this.el).)

* * *

Another solution (perhaps the most natural in the end, however requiring a bit of work at first) is to create a PostView class, and use it for individual posts and for binding checkbox click event.

To display the posts, in your post list view you go through Posts collection, create a view for each Post instance, and append it to the .listOfPosts element.

You won't need to solve a problem of accessing post's ID anymore, since you would bind the checkbox click event on a PostView. So, in the handler function would be able to find post's ID easily—either through related model (this.model.get('id')) or through view's element ($(this.el).data('postId')).

* * * Update

Now that I generated my posts' DOM independently of Backbone how do I 'retrofit' a view to each post like I mentioned in the question?

I don't want to refactor a ton of client code just to accommodate Backbone. But how do I bind a view to each li??

If you decided to go with MVC and object-oriented JavaScript, you shouldn't manage DOM elements for your posts directly: you create PostView instances, and they, in turn, create corresponding elements, like in todos.js, and fill them with rendered template. (And if you don't want to create elements automatically, Backbone allows you to bind newly created view to the element manually, by specifying el attribute when subclassing. This way, you can bind views to existing elements, for example, on the initial page load.) Any DOM modification related to particular posts should take place inside the PostView class.

Some advantages of OOP approach over DOM-based:

  • Views are more suitable for data storage than DOM elements.

    Note that with your current approach you're using data attributes extensively—for example, to store post's ID. But you don't need to do that if you're operating views: each PostView already knows about its related model, and so you can easily get the post id via, e.g., view.model.get('postId'), as well as any other post data that you want.

    You can also store view-specific data that doesn't belong to Post model: for example, animation and / or display state (expanded, selected, …).

  • Views are more suitable for defining the behaviour of elements.

    If you want to, for example, specify a checkbox click event handler for each post, you place this code into your PostView class. This way, event handler knows about all post data, because the view has access to it. Also, the code is better structured—what deals with particular posts, belongs to PostView, and doesn't get in your way.

    Another example is a convention to define a render() function on the view. The template function or template string is stored in a view attribute template, and render() renders that template and fills the view's element with resulting HTML:

    render: function() {
        $(this.el).html(this.template({
            modelData: this.model.toJSON()
        }));
    },
    
  • Manipulating DOM may be slower than manipulating objects.

However, DOM-based approach (which seems like you were using until now) has its own pros, especially for less complicated applications. See also: Object Oriented Javascript vs. Pure jQuery and .data storage

Is there a way to bind views to current and future DOM elements that are NOT generated by backbone?

Does that imply that backbone needs to be use from the very start and will be difficult to 'retrofit' so to speak?

As follows from above, you don't need to bind views to future DOM elements (use views to manipulate them).

Regarding binding to the DOM elements that are already on the page when it's initialized, I don't know the ‘right’ way to do that. My current approach is to clear existing elements and create views from scratch, which would automatically create corresponding DOM elements.

This means browser will have some extra work to do at page initialization. For me, advantages of OOP justify it. From the user's point of view, it's also fine, I guess: after that initial initialization, everything will work faster, since page won't need to be reloaded until user does something like logout.

(BTW, I think I should clarify the point of using MVC approach, at least, for me: creating a client-side application that, essentially, does the most work by itself, using the API provided by the back-end server. Server provides data in JSON for models, and your client-side app does the rest, extensively using AJAX. If you do normal page loads when user interacts with your site, then such MVC and heavy client-side might be overhead for you. Another thing is that you will have to refactor some code, which may not be an option depending on your requirements and resources.)

like image 160
Anton Strogonoff Avatar answered Oct 01 '22 02:10

Anton Strogonoff


Note that events pass reference to themselves and their point of origin, it's the easiest way to access the origination of the event, in my opinion.

Try it like this, and see if this is what you need (and less convoluted):

var MyView = Backbone.View.extend({

    el:$('.listOfPosts'),

    initialize: function() {
         _.bindAll(this,"postClicked");
    },

    events: {
        "click .wcCheckbox":"postClicked"
    },

    postClicked: function(e) {
        alert("Here is my event origin: "+e.target);
    }

});

There is a rich amount of data that can be had from the event, as can be seen here: http://www.quirksmode.org/js/events_properties.html

once you get your head wrapped around javascript eventing, you might look into PubSub/Observer pattern for more-decoupled UI components, here is a good introduction:

http://blog.bobcravens.com/2011/01/loosely-coupled-javascript-using-pubsub/

like image 22
Brendan Lee Avatar answered Oct 01 '22 02:10

Brendan Lee