jQuery - Own plugin - need small help - javascript

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.

Related

how Inject/overrid code in function? best practice?

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])
}

Function/dom calls in javascript library

I'm trying to create a javascript library like jquery. I get how to create a normal library like so:
var lib=lib||(function () {
function privateFunction (alert ("hi");){};
return {
exampleAlert: function(input){
alert(input);
}
}
})();
Calling it like so:
lib.exampleAlert ("test");
This is like jquery
$.ajax(stuffhere);
My question revolves around jquery. It can call the dom like $('.class').hide() and have functions like $.ajax(stuffhere); in the same library. How can I do dom calls and a regular function call like the ajax one in the above example library?
Thanks in advance!! Have searched more days than I would like to admit.
DOM has nothing to do here, it is just up to jQuery implementation.
If you ask about having both lib() and lib.func() calls, then you can do the following to support both function types at the same time:
var lib = function(sel) {
return {
object: document.querySelector(sel),
text: function(val) {
if (val === undefined) {
return this.object.innerText;
} else {
this.object.innerText = val;
}
}
};
};
lib.ajax = function() {
console.log("AJAX imitation");
};
Now, you can do both:
lib("body").text("hi"); // jQuery-style setter
var text = lib("body").text(); // jQuery-style getter, returns "hi"
and
lib.ajax();
jQuery works exactly in the same way, but hundred times more complex.

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();
}
});
});

Adding functions to object parameters

I have around 50 objects like:
object[0].one = something;
object[0].two = else;
object[0].options = whatever;
Not sure how to describe it but they each have sub parameters. I was trying to add an additional parameter that I would add manually only to those I wanted too, like so:
object[15].condition = function() { if (something) { then do something; } } ;
//and then later on in a function do
if (this.condition) {
this.condition;
}
but I can't get it to work =( Is something like this possible? Any help is greatly appreciated.
if (this.condition) {
this.condition();
}

How do I create methods for an HTML element?

I'm trying to create a simple, small and basic javascript framework just for learning purposes.
But the thing is that i'm allready stuck at the very basics.
I'm trying to do something like this:
$('testdiv').testFunction();
And the code i've written for that:
var elementID;
var smallFramework = {
$:function(id) {
this.elementID = id;
},
testFunction:function() {
alert(this.elementID);
}
};
window.$ = smallFramework.$;
But in return I get:
$('testdiv) is undefined
Can anyone help me with this small and hopefully easy question?
To get the behavior you're expecting, you need the $ function to return an object with a method named testFunction.
Try:
var smallFramework = // an object for namespacing
{
$:function(id) // the core function - returns an object wrapping the id
{
return { // return an object literal
elementID: id, // holding the id passed in
testFunction: function() // and a simple method
{
alert(this.elementID);
}
};
}
};
Of course, there are many other ways to achieve the behavior you desire.
If you're trying to add methods to an HTML element you could do something along these lines.
$ = function( elementId ) {
var element = document.getElementById( elementId );
element.testFunction = function(){
alert( this.id );
return this; // for chaining
}
return element;
}
$('test').testFunction();
Try
smallFramework.$('testdiv');
instead. According to the code you posted, that's where your $ function ended up.
Or alternatively, it looks like you're trying to replicate something like jQuery. You might want to try something like this.
var $ = smallFramework = (function () {
var f =
{
find:function(id) {
f.elementID = id;
return f; //every function should return f, for chaining to work
},
testFunction:function() {
alert(f.elementID);
return f;
}
}
return f.find //the find function will be assigned to $.
//and also assigned to smallFramework.
//the find function returns f, so you get access to testFunction via chaining
// like $("blah").testFunction()
})() //note this function gets called immediately.
this code may look confusing to someone new to JavaScript because it depends heavily on the concept of closures. I suggest that if this doesn't make sense, spend some time at Douglas Crockford's JavaScript website. This is important because the code above will bite if you happen to use this in the find function because this won't be bound to f, as you may expect it to be when you use it from $ or smallFramework.

Categories

Resources