Overwrite object methods / functions - javascript

I have the original.js file, but I want to change some things in it. I can't modify original.js, but I can add another better.js file so that I could overwrite some functions of original.js
original.js contains:
MyHandler = {
data:{},
var1:false;
handlers:{},
init:function(handlers){
function1();
function2();
}
function1:function()
{
// function1 code that needs to be replaced
};
}
$(document).ready(function ()
{
///...some code
MyHandler.init();
}
I want to rewrite function1() with new content.
What should I put within better.js file?
P.S. I know better.js should follow after original.js.
I've tried to put the code below to better.js, but it doesn't work (seems like none of function1 work then)
MyHandler = {
function1:function()
{
// new code
};
}
What am I doing wrong?

Just do like this:
if (!MyHandler) { MyHandler = {};}
MyHandler.function1 = function() { ... };
Or you can use jQuery $.extend api method.

Related

Calling a custom function in JQuery

I want to call a JavaScript function that I made after a JQuery event has been called. I defined a function called scrambleDot earlier like this var scrambleDot = new function()
{ //my code }. Here's the code that I tried to use:
$('#reveal').click(function() {
$('.cover').css({'visibility':'hidden'});
$('#under').css({'visibility':'visible'});
})
$('#conceal').click(function() {
$('scrambleDot');
})
})
You have to call it just like:
scrambleDot();
To define a function, you don't need the new operator, so you should have:
var scrambleDot = function() { //my code }
If it still throws an error, it means it was defined in other scope. To make it globally accesible, do this when defining it:
window.scrambleDot = function() { //my code }
Cheers
We have to use new keyword, only when the function is used as a constructor for new Objects. So, the definition should not use new.
var scrambleDot = function() { //my code }
If the function need not be created dynamically, I would recommend
function scrambleDot() {
...
}
To invoke the function, simply do
scrambleDot();
For that call the function instead of selecting an element as:
$('#reveal').click(function() {
$('.cover').css({'visibility':'hidden'});
$('#under').css({'visibility':'visible'});
})
$('#conceal').click(function() {
scrambleDot();
});
And also, you write functions as:
function scrambleDot () {
// your code
}
It is a better practice than the variable one.

How to mangage javascript files and encapsulate JavaScript/jQuery functions

I need to write & manage a lot of JavaScript code for current project.
I separate them into multiple .js files mainly based on module.
So, now i have for example:
Map.js // deal with google map issue
Common.js // common functions that will share by all modules
User.js // user module js code
Geofence.js // geofence module js code
etc.....
For example, inside my User.js file
what if i want to declare a function that only used inside the User.js file, not accessible by outside. what can i do?
var User = {};
User.registerModule = function () {
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
function getAllUsers(){ // how to hide this function
// get
return users;
}
So, in my home page, i only need to coordinate with multiple .js files. Access what allows to access.
$(document).ready(function (data) {
GoogleMap.initialiseGoogleMap();
Common.refreshRightScrollbar();
User.registerModule();
// ...
});
It is my first time to write js and not enough time to study a whole book. So, please, in your opinion, is this structure ok with many js code? and how to hide functions that i dont want outside to access?
to hide that function you have different possibilities
just enclose your code in an immediate self-executed anonymous function
var User = {}; // this should not be enclosed too
(function() {
User.registerModule = function () {
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
function getAllUsers(){ // how to hide this function
// get
return users;
}
})();
enclose that function inside User.registerModule function
User.registerModule = function () {
function getAllUsers() { ... }
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
Place this function inside the scope:
User.registerModule = function () {
function getAllUsers(){ // how to hide this function
// get
return users;
}
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers(); // returns users
// ...
});
}
And it will be private.
Now if you try to call this function outside it will be undefined:
getAllUsers(); // undefined.

How to manually execute a function inside a jQuery plugin?

I have a plugin that looks like this:
(function($) {
$.fn.plugin_name = function(options) {
var $this = $(this);
var defaults = {
// some defaults
};
options = $.extend({}, defaults, options);
var work = {
action_1: function() {
// do something
},
action_2: function(output) {
alert('hello world');
}
}
that.submit(function(e) {
e.preventDefault();
work.action_1();
});
return $this;
}
})(jQuery);
It's being used like any traditional jquery plugin, by being attached to a page element like so:
$('#search-form').plugin_name({
// overide options
});
My question is, how can I execute the work.action_2() function that's deeply nested inside the plugin? I would like to call it manually from the javascript console in firebug.
My question is, how can I execute the work.action_2() function that's deeply nested inside the plugin?
You can't, it's outside of your scope!
you can't reach private function variables, just like you can't reach my functions...
Create it in a separate utility function if its needed independently, better if its in your own global object.
So you can call it like so: $.myGlobalObj.action_2()

jQuery extend an event variable

The plugin has this variable
this.onValid = options.onValid || function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); };
The problem is,when i define a new instance I want to add a new function to this.onValid, I don't want to override the default events?
How can I extend the variable this.onValid ?
this.onValid = options.onValid || function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); };
//That above is already defined;
this._onValid = this.onValid; //Make a backup function
this.onValid = function (){
this._onValid(); //Call the actual function
//Your extended code here //Call your code
}
That was specific to your code. To understand it better, maybe this example will help:
writeA = function (){
document.write('a');
};
//Now I want to extend the writeA function to write 'b' as well
_writeA = writeA;
writeA = function (){
_writeA(); //So now I call whatever the function originally did
document.write('b'); //And now I execute what I want to add to the function
};
Example's demo
Just tried fixing the code you provided in the comment. Try this:
var obj1 = {
this._onValid = this.onValid; //Do this assuming this.onValid is already defined
onValid: function(){ //Redefine it
this._onValid();
newFunction();
}
};
Edit
From the plugin. Just edit it to look like this:
this.onValid = options.onValid || function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); };
this._onValid = this.onValid;
this.onValid = function (){
this._onValid();
//YOUR CODE HERE
};
I have edited the original file to look like that here.
Hah, just realized I put the same code as I had in the beginning here. Well, that's because that's exactly how it should look. See my edited file and search for //YOUR CODE HERE and add your code there.

Javascript object name usage issue.. i think

So i'm setting up an object with private and public methods. Basically using the following format:
var Utility = function() {
var prive1, priv2, priv3;
function privateMethod1() { //do something }
return {
publicFunc1: function() { //do something different }
publicFunc2: function() { //do something else }
}
}
But i'm worried about some of the situations i'm coming across where publicFunc2 needs to call publicFunc1. For Example the way I would do this atm is:
publicFunc2: function() { Utility.publicFunc1(); //then do something else }
is this OK? It runs, but it seems weird and VS2010 doesn't give me . I believe that if someone was to change the line
var Utility = function() { --> to --> var Utility2 = function() {}
then essentially everything would be broken from within the object and that seems wrong...
but i'm at a loss on what i should actually be changing.
Should i be making all methods basically private and then mapping to a public function? EX:
{
function privateFunc1() {}
return {
publicFunc1 : privatefunc1
}
}
or should i have a completely different approach to accomplish the idea of private and public methods and variables?
return {
publicFunc1: function() { },
publicFunc2: function() { this.publicFunc1() }
}
If you want to call some function - give it a name and call it by that name:
var Utility = function() {
var prive1, priv2, priv3;
function privateMethod1() { //do something }
function Func1() { //do something different }
function Func2() { Func1(); //do something else }
return {
publicFunc1: Func1,
publicFunc2: Func2
};
}
Call of local function by name is always faster than any other method of call in JS.
In cases like this remember the YAGNI (You ain't going to need it) concept. Sure, think about the best way to organise things but code for now intially and then refactor it later if needed.
Do the functions need to public or are you second guessing the functionality that may be needed later? Make them private, have a single public method for now. Refactor later if needed. Keep it simple.

Categories

Resources