Is Using Javascript inside a jQuery function is a bad practice? - javascript

I know basics of both jQuery and JavaScript.I would like to follow a good coding practice. Is using JavaScript inside a jQuery function is a bad practice?
For exapmle:
$(document).ready( function() {
$('#dqualification').change(function() {
document.getElementById("demo").innerHTML = "Resolve following errors";
});
});

Nope, its fine, and it's done all the time.
Consider:
$("#myDiv").on("click", function(){
var a = this;
});
The line var a = this; is pure JavaScript. There is no "jQuery Version" of var a = this;.
jQuery provides convenient ways of doing things in JavaScript that might be difficult to write and code yourself in pure JavaScript. It doesn't replace JavaScript, it just 'adds to it'.
Remember, jQuery is just a JavaScript library. So everything ends up as JavaScript at the end of the day.

It is not directly bad practice, it is more a bit inconsistend. Both is javascript. But why would you do things like in your example? If you have jQuery available, you could use it!
$(function() {
$('#dqualification').change(function() {
$("#demo").html("Resolve following errors");
});
});

Related

Best way to organize a javascript application

I have been trying out some different ways to organize my code in my javascript applications and i wonder which one is the most appropriate.
First example:
var Application = {
init: function() {
//Some code
Calculate();
},
Calculate: function() {
//Some code
}
};
Second example:
(function() {
function init() {
//Some code
Calculate();
}
function Calculate() {
//Some code
}
})();
Third example:
(function() {
var init = function() {
//Some code
Calculate();
};
var Calculate = function() {
//Some code
};
})();
Or is it some other way that is preferred? I get very confused over this. Thanks in advance!
The answer is, without question, "it depends." How big is your application? Do you need all of the modules all of the time? How scalable and reusable does your app need to be? These are not JavaScript questions specifically, but rather "architectural" questions, and while learning JavaScript basics is relatively easy, it takes a lot of years to learn to be a good architect in software development. (though it is excellent that you are asking these questions.)
I would encourage you to dive into programming patterns. Learning patterns is learning to structure an application in the right way, depending on the given application.
I can say that a combination of your first example and your second example are a good place to start (an instantly invoked function expression wrapping and returning an object literal). This gives a degree of private scope via closure, and is called the Module Pattern. You will see this pattern used to some degree in almost all major JS applications and libraries because of its versatility and elegance.
To learn more about JavaScript patterns, I highly recommend Addy Osmani's "Learning JavaScript Design Patterns." You can read it for free, here: http://addyosmani.com/resources/essentialjsdesignpatterns/book/

How to use g:message from Javascript

There are some messages coming from a Javascript file to a GSP page. How can I implement g:message in a Javascript page?
For example:
if ($('#name').val() == "") {
$('#nameStatus').show();
$('#nameStatus').html('<font color=red>Company Name can not be blank</font>');
return false;
Try this kind of syntax :
function foo() {
return "${message(code:'my.message.code')}";
}
If I understand correctly, you want to be able to use the output from g:message in your javascript.
There is a very helpful blog post which talks about how to use g:createLink in a similar way that you want, so you can easily adapt it to use g:message as well. Check out the post here, there is some useful info in the comments as well.
The idea is to create javascript objects in your GSP file; which should be defined before including your javascript file; and then just access those global objects in your js code.
Edit:
You might also be interested in the GSParse Plugin. I haven't tried it my self but I think it accomplishes what you are looking for as well.

Add function to existing JQuery plugin

Is it possible to add a function to a plugin without modifying the actual plugin? Can I do something like this in my site's js file?
$.fn.Watermark.Refresh = function() {
$.Watermark.HideAll();
$.Watermark.ShowAll();
}
or
(function($){
$.fn.Watermark.Refresh = function() {
$.Watermark.HideAll();
$.Watermark.ShowAll();
};
})(jQuery);
neither worked, the first says $ is undefined, the second that jQuery is undefined...
ideas?
Solution: Either method works, just include the jquery file before the site js file.
You can add those functions if you want to, but you'll have to make sure that you're also loading jQuery itself and the plugin to be modified. If you're getting those errors (that jQuery or "$" are not defined), then you have not correctly done that.
Now, though it's true that you can add those functions, I have to wonder what the point would be. If I were to do this, for example:
$.fn.css.myFunction = function() { return "hello world"; };
then it would be possible to call it:
var str = $.fn.css.myFunction();
but so what? What good does that do me? I don't think it's very useful.
Make sure you are including the plugin after jQuery.

How to use javascript namespaces correctly in a View / PartialView

i've been playing with MVC for a while now, but since the project i'm on is starting to get wind in its sails more and more people are added to it. Since i'm in charge of hacking around to find out some "best practice", i'm especially wary about the possible misuses of javascript and would like to find out what would be the best way to have our views and partial views play nicely with javascript.
For the moment, we're having code that looks like this (only simplified for example's sake)
<script type="text/javascript">
function DisableInputsForSubmit() {
if ($('#IsDisabled').is(':checked')) {
$('#Parameters :input').attr('disabled', true);
} else {
$('#Parameters :input').removeAttr('disabled');
}
}
</script>
<%=Html.SubmitButton("submit", Html.ResourceText("submit"), New With {.class = "button", .onclick = "DisableInputsForSubmit(); if ($('#EditParameters').validate().form()) {SetContentArea(GetHtmlDisplay('SaveParameters', 'Area', 'Controller'), $('#Parameters').serialize());} return false;"})%><%=Html.ResourceIcon("Save")%>
Here, we're saving a form and posting it to the server, but we disable inputs we don't want to validate if a checkbox is checked.
a bit of context
Please ignore the Html.Resource* bits, it's the resource management
helpers
The SetContentArea method wraps ajax calls, and GetHtmlDisplay
resolves url regarding an area,
controller and action
We've got combres installed that takes care of compressing, minifying
and serving third-parties libraries and what i've clearly identified as reusable javascript
My problem is that if somebody else defines a function DisableInputsForSubmit at another level (let's say the master page, or in another javascript file), problems may arise.
Lots of videos on the web (Resig on the design of jQuery, or Douglas Crockford for his talk at Google about the good parts of javascript) talk about using the namespaces in your libraries/frameworks.
So far so good, but in this case, it looks a bit overkill. What is the recommended way to go? Should i:
Create a whole framework inside a namespace, and reference it globally in the application? Looks like a lot of work for something so tiny as this method
Create a skeleton framework, and use local javascript in my views/partials, eventually promoting parts of the inline javascript to framework status, depending on the usage we have? In this case, how can i cleanly isolate the inline javascript from other views/partials?
Don't worry and rely on UI testing to catch the problem if it ever happens?
As a matter of fact, i think that even the JS code i've written that is in a separate file will benefit from your answers :)
As a matter of safety/best practice, you should always use the module pattern. If you also use event handlers rather than shoving javascript into the onclick attribute, you don't have to worry about naming conflicts and your js is easier to read:
<script type="text/javascript">
(function() {
// your button selector may be different
$("input[type='submit'].button").click(function(ev) {
DisableInputsForSubmit();
if ($('#EditParameters').validate().form()) {
SetContentArea(GetHtmlDisplay('SaveParameters', 'Area','Controller'), $('#Parameters').serialize());
}
ev.preventDefault();
});
function DisableInputsForSubmit() {
if ($('#IsDisabled').is(':checked')) {
$('#Parameters :input').attr('disabled', true);
} else {
$('#Parameters :input').removeAttr('disabled');
}
}
})();
</script>
This is trivially easy to extract into an external file if you decide to.
Edit in response to comment:
To make a function re-usable, I would just use a namespace, yes. Something like this:
(function() {
MyNS = MyNS || {};
MyNS.DisableInputsForSubmit = function() {
//yada yada
}
})();

Getting jQuery to work in Jetpack

I am experimenting with Jetpack and I would like to parse all the years in a given html page and then wrap the year with a link to the Wiki page. I tried the code in jquery and there it works but now I am using it in Jetpack and it gives an error $(doc).replace is not a function. I am definitely new to Jquery / Jetpack so maybe I am missing something really easy but your help is much appreciated.
EDIT: I have tried the suggestions but I am still stuck. The weird thing is that this
JQuery function works:
(function($) {
$.fn.clickUrl = function() {
var regexp = /([1-2][0-9][0-9][0-9])/gi;
this.each(function() {
$(this).html(
$(this).html().replace(regexp,'<ahref=\"http://nl.wikipedia.org/wiki/$1\">$1<\/a>')
);
});
return $(this);
}
})(jQuery);
and basically, I would like to 'port' this function to Jetpack.
This is the 'old' non-working port of my JQuery function to Jetpack:
jetpack.statusBar.append({
html: "Hyperlink Years",
width: 80,
onReady: function(widget){
$(widget).click(function(){
var regexp = /([1-2][0-9][0-9][0-9])/gi;
var doc = jetpack.tabs.focused.contentDocument;
$(doc).each(function() {
$(this).html(
$(doc).replace(regexp,'<a href=\"http://nl.wikipedia.org/wiki/$1\">$1<\/a>'));
});
return $(doc);
});
}
});
I'm not familiar with jetpack, but your jquery seems to be quite messed up.
If "doc" is an HTML document, then doing $(doc).each() doesn't really make sense. It would only loop once, and "this" would be the same as doc.
Then later you are doing $(doc).replace(regexp, ...), but replace() is not a jquery function. You might have wanted to do .html().replace(regexp, ...); HOWEVER, I do not recommend doing this because it will not work - you will just end up replacing any numbers in the document, even if they are part of another URL or the HTML of the page.
For more information, refer to this question or google for jquery text nodes:
Find text string using jQuery?

Categories

Resources