how Inject/overrid code in function? best practice? - javascript

I got a big js lib witch I dont want to change because when they update the code I must update every time as well. So I want to inject or override as little as possible. And get my code in.
The code of the lib and my code in it looks like this:
var Erizo = {}
Erizo.Stream = function (spec) {
var that = Erizo.EventDispatcher(spec);
that.init = function (succesCallBack) {
Erizo.GetUserMedia(opt, function (stream) {
[...]
MY CODE
[...]
}
}
[...]
}
Is there a way to inject my code and dont override the hole Erizo.Stream function? Because this function is very big.
Thanks

You should do something like this:
var oldFunction = Erizo.GetUserMedia
Erizo.GetUserMedia = function(opt, callback){
console.log("code injected")
oldFunction.apply(this,[opt, callback])
}

Related

Best way to perform JavaScript code on specific pages/body class?

I know there are libraries made for this, such as require.js, but I don't want anything complicated. I just want to run JS code that runs when there is a specific class on the body.
My try at this was to create functions for each page code, and a function to check if the body has the class name to execute code, then run it.
var body = $('body');
initPageOnClass('.home', initFrontPage());
function initPageOnClass(className, func) {
if (body.hasClass(className)) {
return func;
}
}
function initFrontPage(){
// some code for the frontpage
}
Which works, but I fear this may be bad practice. Is it? I know the more pages there is, there will be more functions:
initPageOnClass('.home', initAboutPage());
initPageOnClass('.subscriptions', initSubscriptionPage());
initPageOnClass('.team', initTeamPage());
But I'm not sure if this would be a big no, or what. I want to do this properly.
What is the correct or best way to perform this task?
Id rather use some attribute in this case and map of functions. Your markup will have role attribute defined:
<body role=home>...</body>
And the script may look like:
var initMap = {
'home':initAboutPage,
'subscriptions': initSubscriptionPage,
'team': initTeamPage };
// getting initializer function by content of 'role' attribute
var initializer = initMap[ $('body').attr('role') ] || initAboutPage;
initializer();
And yet check my spapp - it's quite simple (60 LOC)
I think you're on the right path, but not quite executing properly and if you're going to have a bunch of different classes/functions that you check for, then I'd suggest a table driven approach, so you can maintain it by just adding/removing/modifying items in the table rather than writing new code:
var bodyClassList = {
"home": initFrontPage,
"subscriptions": initSubscriptionPage,
"team": initTeamPage
};
function runBodyInit() {
var body = $(document.body);
$.each(bodyClassList, function(cls, fn) {
if (body.hasClass(cls) {
// if class found, execute corresponding function
fn();
}
});
}
runBodyInit();
Or, if you're doing this on document.ready, then you might do this:
$(document).ready(function() {
var bodyClassList = {
"home": initFrontPage,
"subscriptions": initSubscriptionPage,
"team": initTeamPage
};
var body = $(document.body);
$.each(bodyClassList, function(cls, fn) {
if (body.hasClass(cls) {
// if class found, execute corresponding function
fn();
}
});
});

how to get a property name which represent a function in JS

This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc

TAFFYdb: Passing in options to a function

update: This code is bonkers. The root of the issue here is recreating the name of a variable by concating strings and assuming it would then magically turn into that variable.. I had a lot to learn. Also, a much better way to pass an ambiguous number of options into a function is to use JSON.
var availableTimes,
selected_unit,
selected_unit_number;
function createTimePicker(machineNumber){
availableTimes = machineNumber({booked:"no"}).select("time");
for (i=0;i<availableTimes.length;i++){
$('<option/>').val(availableTimes[i]).html(availableTimes[i]).appendTo('#signin_start_time');
}
}
$(function() {
$('body').on('click', '#cybex_arctrainer_button', function() {
selected_unit = "cybex_arctrainer";
});
$('body').on('change', '#signin_unit_number_selector', function () {
selected_unit_number = $("#signin_unit_number_selector option:selected").text();
unit_plus_number = selected_unit+selected_unit_number;
createTimePicker(unit_plus_number);
});
});
A few things: The database works. If I run createTimePicker(cybex_arctrainer1) it fills in the availableTimes variable just fine. The problem seems to be with combining selected_unit+selected_unit_number and passing them to createTimePicker.
Here:
machineNumber({booked:"no"})
machineNumber is a string, but you're trying to call it as if it is a function. You'll get the same error if you do something like
someVar = 'bob';
someVar();
You say that if you run
createTimePicker(cybex_arctrainer1);
but your code is not calling createTimePicker with the variable cybex_arctrainer1 as an argument, instead it's doing something more like:
createTimePicker('cybex_arctrainer1');

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.

jQuery - Own plugin - need small help

I created my own jQuery plugin in 1.4 and now I need a small amount of help.
$.etrade = function()
{
}
I need so I can build code like this
$.etrade = function()
{
this.var = 'setting';
this.subfunction = function()
{
};
}
when I take function from my plugin I need to use it like this:
$.etrade.var = '5';
$.etrade.subfunction();
Somebody know what I mean? and how I can get this problem done? :)
It sounds like you want to assign a plain old object to $.etrade, not a function. Like this:
$.etrade = {
variable: 'setting',
otherVariable: 'something else',
subfunction: function () { /* do stuff here */ },
anotherSubFunction: function () { /* do other stuff here */ }
}
That said, I'm not sure how this qualifies as a jQuery plugin, since it looks like you're just tacking an ad-hoc property onto jQuery.
Aside: you can't use var as per your example, since it's a keyword in JavaScript.

Categories

Resources