Search code examples
javascriptjquerybackbone.js

What to use instead of "this" in Backbone.js?


Here's my code:

if ($(this.el).find('.select-picture').is(':checked')) {
    var source = $(this).parent().prev().attr('src');
    document.cookie = "imagePath=" + source;
    var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)imagePath\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    console.log(myCookie);
}

I have a class .select-picture and I'm looking for it's parent's previous element and I want to perform an action on it (save the image path to a cookie). The code works nicely when put between tags in html document, but when putting it in Backbone's view the console returns "undefined".

I'm almost sure it's because "this" in Backbone is not what "this" was in its previous place, but I don't know how to change it to make it work.

Could somebody help me?

EDIT - this is HTML:

 <div class="img-holder">
     <img src="images/picture.jpg" class="img-responsive top-img choose-img"/>
     <form>
         <input type="radio" name="vehicle" value="Bike" class="select-picture">
      </form>
 </div>
 <div class="img-holder">
      <img src="images/picture2.jpg" class="img-responsive choose-img"/>
      <form>
         <input type="radio" name="vehicle" value="Bike" class="select-picture">
      </form>
 </div>

Solution

  • It's important to understanding scope and context in javascript. I suppose your template is something like this :

    <script id="template_id" type="text/template">
    <div>
    
        <% _.each(images, function(image){ %>
          <div class="row">
            <img src="<%= image.src %>" />
            <div class="form-group"> 
                <input class="select-picture" name="image[<%= image.uid %>]['is_checked']" type="checkbox" />          
                <input name="image[<%= image.uid %>]['quantity']" type="text" />  
            </div>
          <div> 
        <% }); %>
    </div>
    </script>
    

    In you Backbone View you can do something like that :

    Backbone.View.extend({
    
       el : $('#template_id'),
    
       function onChecked(){
          /* 
           *  this.$el refer to #template_id element.
           */
          this.$el.find('.select-picture:checked').each(function(index){
               /* 
                * Now this referer to the current context.  
                */
               var source = $(this).parent().prev().attr('src');
               document.cookie = "imagePath=" + source;
               var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)imagePath\s*\=\s*([^;]*).*$)|^.*$/, "$1");
               console.log(myCookie);
          })
       },
    });
    

    Take a look at :