做一个功能,jquery实现很简单
$(".variant_list").find("li").each(function(){
$(this).click(function() {
$(this).siblings('li').removeClass('active')
$(this).addClass('active')
$('#product_property').val($(this).attr('data-id'))
parentDom.priceChange($(this).attr('data-id'))
});
});
但在es6中就比较麻烦
export default class CartProperty {
static defaults = {
actionMethod: 'POST',
productPriceId: '#product_price',
productNumUrl: '/api/carts/updateprice',
productCurrentId: '#product_id',
productNumId: '#product_num',
productPropertyId: '#product_property'
}
constructor(element) {
this.$element = $(element)
this.options = $.extend({}, CartProperty.defaults, this.$element.data())
// 当前显示的价格
this.$productPriceId = $(this.options.productPriceId)
// 当前的product id
this.$productId = $(this.options.productCurrentId).val()
// 当前num
this.$productNumVal = $(this.options.productNumId).val()
// 当前规格的隐藏域
this.$productPropertyId = $(this.options.productPropertyId)
}
init() {
this.propertyChange()
}
propertyChange = () => {
this.$element.find('li').each(function () {
$(this).on('click', () => {
$(this).siblings('li').removeClass('active')
$(this).addClass('active')
$('#product_property').val($(this).attr('data-id'))
})
})
}
priceChange = (currentProperty) => {
// ajax获取价格
const ajaxOptions = {
method: this.options.actionMethod,
data: {
number: this.$productNumVal,
property: currentProperty,
id: this.$productId
}
}
console.log(currentProperty)
if (this.options.actionWithToken) {
ajaxOptions.headers = {
Authorization: getToken(),
}
}
$.ajax(this.options.productNumUrl, ajaxOptions).done((data) => {
this.$productPriceId.html(`¥${data.price}`)
}).fail(() => {
window.location.href = '/login'
})
}
}
上面代码中的this指向了class CartProperty, 但propertyChange中each的this指向啦each的li,现在我想在click中调用priceChange,肯定使用this是调用不了的,刚开始想到啦self,但self指向了window,后来我就想需要个东西把this指引进来:
propertyChange = (parentDom) => {
this.$element.find('li').each(function () {
$(this).on('click', () => {
$(this).siblings('li').removeClass('active')
$(this).addClass('active')
$('#product_property').val($(this).attr('data-id'))
parentDom.priceChange($(this).attr('data-id'))
})
})
}
这里我用parentDom把this指引进来,同样的,调用这个function的地方需要传入this
init() {
this.propertyChange(this)
}