缺少上下文Javascript

时间:2015-06-04 11:09:28

标签: javascript jquery javascript-events

我有一个方法_addEvents,它使用JQuery on.函数为按钮设置click事件。这也为cartCollection.removeItem(buttonId);提供了点击按钮的ID。问题是它保持失去按钮的id值并给出undefined

EDITED _addEvents必须从此模板中获取点击按钮的ID:

<script type="text/template" id="cartTemplate">
<ul id = "cartList" >
    <% for(var i = 0; i < data.items.length; i++){%>
    <%if(data.items[i].quantity === 1){%>
    <li><%=data.items[i].item.id%><br>
        <%=data.items[i].item.name%><br>
        Price per Phone:<%=data.items[i].item.price%><br>
        <%=data.items[i].thisItemTotal %><br>
        Total Quantity:<%=data.TotalQuantity%><br>
        Total Price:<%=data.total%><br>
        <button id="<%=data.items[i].item.id%>" type="button" class="removeButton btn btn-default" aria-label="center-align">
            Remove
        </button>
    </li>
    <%} else {%>
    <li><%=data.items[i].item.id%><br>
        <%=data.items[i].item.name%><br>
        Quantity:<%=data.items[i].quantity%><br>
        Price per Phone:<%=data.items[i].item.price%><br>
        <%=data.items[i].thisItemTotal %><br>
        Total Quantity:<%=data.TotalQuantity%><br>
        Total Price:<%=data.total%><br>
        <button id="<%=data.items[i].item.id%>" type="button" class="removeButton btn btn-default" aria-label="center-align">
            Remove
        </button>
    </li>
    <%}%>
    <%}%>
</ul>

_addEvents的实现以及该方法所属的对象:

var cartList = {
_itemsCollections: cartCollection,
_template: _.template($('#cartTemplate').html()),
_rootElement: $('#ordersCartDiv'),
//_rootElementUl: $("#cartList"),
initialize: function () {
    'use strict';
    //this.divId = divId;
    //this._rootElementUl = $("#cartList");
    //this._itemsCollections= cartCollection;
    //bind(this._addEvents(),cartList);
    this._addEvents();
},
render: function () {
    'use strict';
    var data = {
        items: this._itemsCollections.getItems(),
        total: this._itemsCollections.getTotalPrice(),
        TotalQuantity: this._itemsCollections.getTotalQuantity()
    };
    var rendTemplate = this._template({data: data});
    this._rootElement.html(rendTemplate);
    this._addEvents();
    console.log(this._itemsCollections);
},
_addEvents: function () {
    'use strict';
    var self = this;
    this._rootElement.on('click','.removeButton' , function () {
        var buttonId = $(self).attr('id'); // undefined
        console.log('id:' + buttonId);
        cartCollection.removeItem(buttonId);
        cartList.render();
    });
}

};

1 个答案:

答案 0 :(得分:3)

好的 - 你的this引用了回调上下文,你应该从事件对象中获取被点击的对象:

_addEvents: function () {
    'use strict';
    this._rootElement.on('click','.removeButton' , function ( e ) {
        var buttonId = $( e.currentTarget ).attr('id'); // GET TARGET FROM EVENT
        console.log('id:' + buttonId);
        cartCollection.removeItem(buttonId);
        cartList.render();
    });
}