In my current application I am using jquery UI dialog at many places , so I am planning to create a method like
var MYAPP = MYAPP || {};
MYAPP.overlay = (function(){
$("#id").dialog();
}());
This is my idea but now the problem is my overlay is used for different purpose like overlay form, video, confirmation message etc. Is there a way I can have all the option inside my API . so I just have to call MYAPP.overlay("video",some other parameter) and it will create the overlay without have to repeat the code again and again....any idea or suggestion will be appreciated..
I'm not sure what you are trying to accomplish with the immediately executing anonymous function, but you can do something like this:
MYAPP.overlay = function MYAPP$overlay(id, paramsObj) {
// do something based on element type, id, or params obj here.
$(id).dialog();
// possibly return something if needed.
};
yes you can use parameters. here is a very generic way of doing it:
MYAPP.overlay = (function(){
// complex code ....
return function(arg) {
alert(arg);
}
})();
// example
MYAPP.overlay('hello');
will alert hello
Related
I try to build a small tool for get the structure of my js running in a browser.
I create a gits for that: https://gist.github.com/M3kH/6615963
But is no way to make work on the browser without crashes.
What you think I'm doing wrong?
Did you think Async way would prevent browser crashes?
How can I get the property of a element is a function? I need to
executed it?
I have some cases like in jquery plugins where looks like:
;(function($, window, document, undefined) {
$.fn.namePlugin = function(options) {
options = $.extend( {}, $.fn.namePlugin.options,options );
return this.each(function(){
// This is the builder
$.fn.namePlugin.options.functionA();
});
}
// Here where I fill all the functions
$.fn.namePlugin.options = { functionA: function(){} };
});
Did you think I have some ways for get the return function as a loop?
I would like to build an utility for get the list of the function, for document it in a second moment.
Thanks in advance,
Mauro.
I have been playing around with dependency injection with javscript but have some questions that I need help with
A simple example is a dialog module I have, used in multiple places on the page it alerts a user with a custom message when a user interacts with a component on the page
function Dialog () {
}
Dialog.prototype.show = function () {
}
and this may be used in a component, say a search control which validates a user search and if its empty it fires an error dialog. With dependency injection I'm assuming I would write:
function searchComponent (dialog) {
this.dialog = dialog
}
searchComponent.prototype.validateSearch = function () {
// validate search if invalid create error
this.dialog.show();
}
var searchDialog = new Dialog();
var search = new searchComponent(searchDialog);
However a user may never need the search error dialog, yet I am creating an instance of it just so that I can then pass the dependency through, what if I have 100 individual instances of a dialog on the page do I construct these 100 times, this is unnecessary and expensive in performance.
what I would rather do is lazy load the construction of a dialog to a time when it is needed
searchComponent.prototype.validateSearch = function () {
//validate search if invalid create error
var dialog = new Dialog();
dialog.show();
}
now I know that this creates disadvantages and one of these is the affects it has on unit testing, what I am keen to understand is whether I have missed something or an alternative method?
Thanks in advance
JavaScript functions are first class objects. Instead of passing in a constructed dialog, pass in the dialog constructor function:
var search = new SearchComponent(Dialog);
Then new it up when you need it:
function SearchComponent(Dialog) {
this.Dialog = Dialog;
}
SearchComponent.prototype.validateSearch = function() {
var dialog = new this.Dialog();
dialog.show();
}
To extend #ChrisTavares' great solution, you can use something like this to make dependency injection inside the Dialog possible as well:
var foo = function () { return new Foo() }; // just an example
var search = new SearchComponent(function() {
return new Dialog(foo());
});
Inside your SearchComponent:
function SearchComponent(Dialog) {
this.Dialog = Dialog;
}
SearchComponent.prototype.validateSearch = function () {
var dialog = new this.Dialog();
dialog.show();
};
Inspired by the previous examples, I've created a simple jsFiddle that utilizes a small library called Syringe.js in order to show how dependencies can be injected by pre-binding the SearchComponent constructor.
When a SearchComponent object is created, the validator dependency (a separate component, here taking the place of an actual dialog) is automatically provisioned. This dependency is subsequently used by the validateSearch method.
The advantage of doing it this way is that you don't have to have any dependencies in your hand when you create each SearchComponent object instance.
In addition, the validator dependency can be modified after theSearchComponent objects are created, and the behavior of the dependent control(s) can be updated accordingly.
I recently wrote a dependency injection library called infect.js. Check it out, might just be what you're looking for. https://github.com/amwmedia/infect.js
After discovering about Javascript namespaces, I tried to implement them but I run into a problem while trying to attach a namespace method to an element's onclick.
I used this method to wrap up my functions/methods/classes (a simplified concept, not my actual code):
;(function(window, undefined) {
//my namespace
var NS = {};
NS.test = {
f : function(param) {
alert(param);
}
}
NS.test.('test 2');
})(window);
Inside, everything works fine and "test 2" is prompted.
However, when I try to attach that function to a click event, by doing something like this:
<a href-"#" onclick="NS.test.f('test');">Click me!</a>
it doesn't work, just like it doesn't work when I call that function after the })(window); part.
I tried it calling it window.NS.test.f('test'); but with no effect.
How can I make an onclick event call my function?
I could attach an event listener inside my wrapper, like I do for other html elements with no difficulty, but it would be problematic in this case since I'm generating the links with javascript and I find it easier and simpler to just add onclick="doSomething" for all my links, instead of creating them, then cache them and add event listeners.
Call me lazy, but in this particular case I prefer to do
someDiv.innerHTML = my_Generated_Html_Code_With_OnClick;
instead of
//demo code, ignore the flaws and the fact it won't work on IE
someDiv.innerHTML = my_generated_Html_code;
myLink = document.getElementById(id);
myLink.addEventListener('mousedown', NS.test.f('test'));
I do not use any framework nor do I wish to, since I'm trying to get a better understanding of the so-called vanilla javascript first.
I set up a jsfiddle here.
P.S. I must admit I didn't understand namespaces completely so if I'm doing something wrong here or applying the concept in a way I am not supposed to, I would appreciate any tips or corrections
That's because NS is declared inside and hence only exists inside the function:
function(window, undefined) {
var NS = {};
// NS exists here ...
}
// ... but not here
If you want to make it available to the rest of the page, then you can do:
function(window, undefined) {
var NS = window.NS = {};
// NS and window.NS exist here ...
}
// ... and window.NS exists here.
Wondering if there is an elegant way to listen for a function in JavaScript and/or jQuery.
Rather than listening for a $('#mything').click(function(){ //blah }) I'd like to listen for when a specific function is fired off. I don't want to edit the function as it's within a library that I don't want to hack directly.
I did find this: http://plugins.jquery.com/project/jqConnect which connects functions.
But wondering about a better technique.
The only way to do this is to override the function (ie, hack the library):
(function() {
var oldVersion = someLibrary.someFunction;
someLibrary.someFunction = function() {
// do some stuff
var result = oldVersion.apply(this, arguments);
// do some more stuff
return result;
};
})();
Edit: To run your code after the library function has run, just call the library function first, storing the result in a variable. Then, run your code, and finally return the previously stored result. I've updated my example above to accomodate running code either before or after the library function.
Perhaps I am doing this wrong and suggestions on how to improve my code are appreciated. My situation is this: I have a toolbar with different elements that are populated by a callback. I do not want to use the show() or hide() commands, I prefer to use detach, but I think there should be a nice way to deal with it. Here's my code:
entryView = function _entryView() {
var menuButton = $('<div/>').addClass('menuButton');
toolBar();
$.getJSON('ajax', function(o) {
var $enum2 = ss.IEnumerator.getEnumerator(dto.TransmittalDates);
while ($enum2.moveNext()) {
var dateTime = $enum2.get_current();
$('.menu').append($('<div/>').addClass('menuitem').text(dateTime.toString()));
}
});
}
toolBar = function _toolBar() {
var flyoutMenu = $('<div/>').addClass('menu');
$('.menuButton').click(function(o) {
$('.menubutton').append(flyoutMenu);
});
I did a quick cut and paste and renamed the variables to make them make sense. As you can see on the entry I build the toolbar and the very last thing I do is the ajax call. The menu, however, is not created until the "click" event, so appending is not possible.
I realize that having global variables is bad, so I'm trying to avoid that, but I think the best situation would have the ajax call populate a Menu variable and when the DOM is created, to pull from that same Menu item. How do I pull this off? Is there a better way to do it?
Edit: Fubbed a bit on the toolbar function, I think I have it should be correct now.
I'm confused by some parts of your code:
What's the entryView function and when is it called?
Why does the toolBar function exist as opposed to being inline? From where else is it called?
Why are you creating functions like that? Creating a variable without var is bad practice, always makes global variables, and will be forbidden in ES5 strict mode. You should create functions like this:
var someFunction = function(arg1, arg2) { … };
or like this:
function someFunction(arg1, arg2) { … }
Why are you giving each function a second name (e.g. _toolBar)? The "private" name will only be in scope inside the function.
The menu doesn't have to be in global scope, just in a scope that's common to both functions.
I would refactor it like this (knowing very little about the design of your application), inlining toolBar:
function entryView() {
var menuButton = $('<div/>' {'class': 'menuButton'}), menu = $('<div/>', {'class': 'menu'});
$.getJSON('ajax', function(o) {
var $enum2 = ss.IEnumerator.getEnumerator(dto.TransmittalDates);
while ($enum2.moveNext()) {
var dateTime = $enum2.get_current();
$('.menu').append($('<div/>' {'class': 'menuItem'}).text(dateTime.toString()));
}
});
menuButton.click(function(o) {
menuButton.append(menu);
});
}