Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override JS function from another file

Im trying to override a JS function from Bigcartel. I have no access to the JS file.

The original is:

updateCart: function(cart) {
    $('aside .cart .count, .main header .cart').htmlHighlight(cart.item_count);
    return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
  }, 

And i am trying to change it to this:

updateCart: function(cart) {
  $('aside .cart .count, .sml .cart, .big .cart .count').htmlHighlight(cart.item_count);
  return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
},

I am aware that others have asked similar questions, but i am a complete noob when it comes to understanding how to implement JS (i only know how to tweek through trial and error)

If any one could be so kind as to help me out by giving me the answer that would be great.

Thanks,

iWed-


EDIT [10.10.13 :: 21:24hr]

To clarify, i do not have direct access to the original JS file. i can only view it through chrome. I only have access to html files. It is for a Big cartel theme Edit.

Here is a link to to copied JS using chrome. Line 216 is the code, if this helps : http://jsfiddle.net/w9GTJ/

like image 823
Wednesday Man Avatar asked Oct 10 '13 16:10

Wednesday Man


1 Answers

EDIT: You are in luck. From the posted code you can see that the updateCart method is exported on the window.Store global object. The solution is to add this code after the original script loaded:

window.Store.updateCart = function(cart) {
  $('aside .cart .count, .sml .cart, .big .cart .count').htmlHighlight(cart.item_count);
  return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
};

Explanation for a general situation:

All scripts loaded in a web page run in the same global scope, so overwriting a variable is as simple as inserting your script afterwards:

<script>
var x = 5; // original script
</script>
<script>
x = 2; // your inserted script
</script>

From the looks of it, your function is defined as property of an object:

var x = {
   updateCart : function(cart) {
     // stuff
   }
}

So to overwrite it you need to do:

x.updateCart = function(cart) {
  // your code
}

Finally, there is one situation where you simply can't overwrite it, if function is private in the original code:

function() {
   var x = {
      updateCart: function(){}
   }
}()

// No way to access x.updateCart here
like image 101
Tibos Avatar answered Oct 06 '22 17:10

Tibos