user1698144
user1698144

Reputation: 764

KnockoutJS, how to add $ symbol to oberservable

Im fairly new to KnockoutJS, so this might not be the most constructive of questions, but I cant seem to figure this out on my own.

How would I add a $ symbol in front of an observable? I've tried a computed observable, but could not get it to work since my data is being pulled from the server

$(document).ready(function () {     

    $(function () {

        function viewModel(cartData) {
            var self = this;
            self.cartItems = ko.observableArray([]);
            self.discountPercent = ko.observable();
            self.grandTotal = ko.observable();

            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            self.removeCartItem = function (CartItem) {
                $.ajax({
                    url: '@Url.Action("RemoveFromCart", "ShoppingCart", null)',
                    type: 'POST',
                    data: { 'ID': CartItem.cartItemID },
                    success: function (data) {
                        self.cartItems.remove(CartItem);
                        self.getCartTotal();
                    }
                });

            };

            //////////////////////////////////////////////////////////////////////////////////////////////////////

            self.getCartTotal = function () {

                $.getJSON('@Url.Action("koGetTotal","ShoppingCart",null)', function (data) {
                    self.grandTotal(data.finalTotal);
                    console.log("getting total");
                });
            };

            //////////////////////////////////////////////////////////////////////////////////////////////////////
            self.addItemToCart = function (listingID, qty) {
                $.ajax({
                    url: '@Url.Action("phoneAdd","ShoppingCart",null)',
                    type: 'POST',
                    data: {
                        'listingID': listingID,
                        'requestedQty': qty
                    },
                    success: function (data) {
                        alert(data.status);
                    }
                });
            };






            self.loadCartData = function () {


                $.getJSON('@Url.Action("koShoppingCartItems","ShoppingCart",null)', function (data) {

                    $.each(data, function () {
                        self.discountPercent(data.length);
                        self.cartItems.push({
                            itemTitle: ko.observable(this.itemTitle),
                            cartItemID: ko.observable(this.cartItemID),
                            price: ko.observable(this.Price),
                            qty: ko.observable(this.Quantity),
                            displayImgPath: ko.observable(this.displayImgPath),
                            lineTotal: ko.observable(this.lineTotal)
                        });
                    });

                });

                self.getCartTotal();
            }

            self.loadCartData();

        }

        ko.applyBindings(new viewModel());

    });
});

Upvotes: 1

Views: 227

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

I assume you're talking about price on item that you're pushing into cart.

In general, formatting is something you want to do with custom binding handlers:

The handler:

ko.bindingHandlers.price = {
    update: function(element, valueAccessor, allBindings) {
        var symbol = allBindings.get("priceSymbol") || "$";
        element.innerHTML = symbol + ko.unwrap(valueAccessor()).toFixed(2);
        // Or possibly even more formatting on that value
    }
};

Using it:

<span data-bind="price: price"></span>

Example:

ko.bindingHandlers.price = {
  update: function(element, valueAccessor, allBindings) {
    var symbol = allBindings.get("priceSymbol") || "$";
    element.innerHTML = symbol + ko.unwrap(valueAccessor()).toFixed(2);
    // Or possibly even more formatting on that value
  }
};

var vm = {
  items: ko.observableArray()
};

ko.applyBindings(vm, document.body);

var counter = 0;
addItem();

function addItem() {
  var price = Math.floor(Math.random() * 10000) / 100;
  ++counter;
  vm.items.push({
    name: "Random item " + counter,
    priceUSD: price,
    priceGBP: price * 0.6
  });
  if (counter < 5) {
    setTimeout(addItem, 500);
  }
}
.currency {
  text-align: right;
  padding-left: 4px;
}
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>USD</th>
      <th>GBP</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: items">
    <tr>
      <td data-bind="text: name"></td>
      <td data-bind="price: priceUSD" class="currency"></td>
      <td data-bind="price: priceGBP, priceSymbol: '£'" class="currency"></td>
  </tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>


But you could use a computed, for instance priceDisplay:

var item = {
    itemTitle: ko.observable(this.itemTitle),
    cartItemID: ko.observable(this.cartItemID),
    price: ko.observable(this.Price),
    qty: ko.observable(this.Quantity),
    displayImgPath: ko.observable(this.displayImgPath),
    lineTotal: ko.observable(this.lineTotal)
};
item.priceDisplay = ko.computed(function() {
  return "$" + this.price();
}, item);
self.cartItems.push(item);

Upvotes: 3

Related Questions