在Backbone.js中使用什么代替“ this”?

一天

这是我的代码:

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

我有一个.select-picture类,我正在寻找它的父级上一个元素,我想对其执行一个操作(将图像路径保存到cookie)。将代码放在html文档中的标记之间时,该代码可以很好地工作,但是将其放在Backbone的视图中时,控制台将返回“ undefined”。

我几乎可以肯定,这是因为Backbone中的“ this”不是以前的“ this”,但是我不知道如何对其进行更改才能使其正常工作。

有人可以帮我吗?

编辑-这是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>
蒂博·雷米(Thibault Remy)

了解javascript中的范围和上下文很重要。我想你的模板是这样的:

<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>

在您的骨干网视图中,您可以执行以下操作:

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);
      })
   },
});

看一眼 :

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章