我有一个addToCart函数,我想利用它不在我的viewModel中。
在我的视图模型中,我有一个对象{"items":[ {"name":"siren","id":2,"image":"s3.amazon.com"}])
在我的淘汰应用中:
<div id="cart" class="shopify-buy__cart-scroll">
<div class="shopify-buy__cart-items" data-bind="foreach: newcart.items">
<div class="shopify-buy__cart-item">
<div data-bind="style: { 'background-image': 'url(' + images + ')'}" class="shopify-buy__cart-item__image" alt="Product" style="background-repeat:no-repeat;background-size: contain;"></div>
<span class="shopify-buy__cart-item__title" data-bind="text: name"></span>
<span class="shopify-buy__cart-item__price" data-bind="text: price "></span>
<div class="shopify-buy__quantity-container">
<button class="shopify-buy__btn--seamless shopify-buy__quantity-decrement" type="button">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M4 7h8v2H4z"></path></svg>
</button>
<input class="shopify-buy__quantity shopify-buy__cart-item__quantity-input" type="number" min="0" aria-label="Quantity" data-bind="attr: {value: quantity}" style="height: 30px; border:solid 1px #d3dbe2 !important;padding-left:13px;" />
<button class="shopify-buy__btn--seamless shopify-buy__quantity-increment" type="button" databind="click: addToCard(id)" >
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M12 7H9V4H7v3H4v2h3v3h2V9h3z"></path></svg>
</button>
</div>
</div>
</div>
<div class="shopify-buy__cart-bottom">
<p class="shopify-buy__cart__subtotal__text" >SUBTOTAL</p>
<p class="shopify-buy__cart__subtotal__price"data-bind="text: total"></p>
<p class="shopify-buy__cart__notice">Shipping and discount codes are added at checkout.</p>
<button class="shopify-buy__btn shopify-buy__btn--cart-checkout" type="button">CHECKOUT</button>
</div>
</div>
在这一行:<button class="shopify-buy__btn--seamless shopify-buy__quantity-decrement" type="button">
我想添加一些带动态参数的函数。
<button class="shopify-buy__btn--seamless shopify-buy__quantity-incriment" type="button" databind="attr: {onclick:addToCart( id ) }">
但这不起作用。如何在不将功能添加到viewmodel的情况下执行此操作。它只是一个对象,我想保持这种方式。
谢谢!
答案 0 :(得分:0)
如何使用html5数据属性。将你的淘汰赛ID带入你的点击功能。
data-bind="attr: {'data-idfromko': id }"
在下方运行代码段。
function model() {
var self = this;
this.theArray = ko.observableArray([{
'id': 1,
'foo': 'bar'
}, {
'id': 2,
'foo': 'bar2'
}, {
'id': 3,
'foo': 'bar3'
}, ]);
}
var mymodel = new model();
$(document).ready(function() {
ko.applyBindings(mymodel);
$('.button').click(function(event) {
value = $(this).data("idfromko" )
alert(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr>
<th>id</th>
<th>foo</th>
<th></th>
</tr>
<</thead>
<tbody data-bind=foreach:theArray>
<tr>
<td data-bind="text:id"></td>
<td data-bind="text:foo"></td>
<td>
<button class="button"
data-bind="attr: {'data-idfromko': id }">
click
</button>
</td>
</tr>
</tbody>
</table>