Is there a way to include a javascript file only once or declare a function only once? The issue I am having is that I have an HTML module that contains a javascript include. Well this module is loaded in a loop, and therefore that file is loaded multiple times. I've worked out most of the kinks, but what bothers me is that I know the same function is getting created multiple times, and this look can be as many as 30 iterations. To me, I don't like the fact that the same function is getting created over and over. Should I care? Is there a way I can prevent this? I know I can detect when a function exists, can I put the function declaration in between an if statement?
Update
I've tried out one of the suggestions:
if(typeof btnSendInvite_click != 'function')
{
function btnSendInvite_click()
{
alert("#invite_guest_" + $(this).attr("event_id"));
return false;
}
}
but that doesn't work. I've also tried
if(!btnSendInvite_click)
{
function btnSendInvite_click()
{
alert("#invite_guest_" + $(this).attr("event_id"));
return false;
}
}
but it doesn't work. What happens is that I have this line:
$(document).ready(function()
{
$(".btnSendInvite").bind("click", btnSendInvite_click);
});
and when the button gets clicked, that functions is executed six times, which is the amount of times that the file was included which tells me that the function is being created multiple times... I think.
Update
So after a lot of struggling, this problem is turning into something different than what I thought. The bind is being called multiple times, so it's getting bound multiple times, and therefore calling the function multiple times. I guess my next question is, is there a way to bind a function to a control only once? I've tried the jquery "one" already and it doesn't work.
Yes, you can (run on jsfiddle).
if (!window.myFunction) {
window.myFunction = function() {
//...
}
}
Edit: In your case it would be:
if (!window.btnSendInvite_click) {
window.btnSendInvite_click = function() {
alert("#invite_guest_" + $(this).attr("event_id"));
return false;
}
}
The call to bind() also has to be somewhere in that conditional block.
Note: The following variant won't work, at least not on all browsers:
if (!window.myFunction) {
function myFunction() {
//...
}
}
Edit 2: For your update:
Declare a variable when you call bind.
if (window.iBoundThatStuff!=true) {
iBoundThatStuff=true;
//call bind() here
}
Having JS included in a loop is ridiculous. Move your JS out of the loop.
JS can tell if function was defined but fixing bad server side loop in JS is definitively a bad practice.
Yes you should worry about not including your script file several times and not to declare the function several times...
For the first part, you may want to look into changing your html structure so the js file is only included once (even though js files are cached by the browser, and the second time may not actually go to the server -- depending of several factors... there's still a penalty)
Now as for declaring your function only once, remember that functions are also object (1st class citizens) in js, so you can test if a function is already define as if you were testing an object.... if(!window.myFunc) { window.myFunc = function(){} }...
You may want to look a bit into functions and scoping in js.. here are some links
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
http://www.yuiblog.com/blog/2010/02/24/video-crockonjs-3/
http://www.slideshare.net/douglascrockford/crockford-on-javascript-act-iii-function-the-ultimate
Related
I have created a project in .fla that was exporting to .swf however I now require it in HTML5 format. So I change the file conversion type and now require my ActionScript3 to be converted to JavaScript. However, This is not my strong suit.
I am currently trying:
this.stop();
this.close1_btn.addEventListener("click", function (closebtn)
{
this.gotoAndPlay(1);
});
this.store1_btn.addEventListener("click", function (store1_btn)
{
this.gotoAndPlay(11);
});
this.store2_btn.addEventListener("click", function (store2_btn)
{
this.gotoAndPlay(12);
});
this.store3_btn.addEventListener("click", function (store3_btn)
{
this.gotoAndPlay(13);
});
OVERVIEW: trying to listen to a symbol e.g close1_btn for clicks. when clicked it will link to and stop at a specified frame.
I expect a few bits to be wrong *maybe near the function () part?
Its a fairly simple map so shouldn't be too hard for someone who knows what they are looking at! Thanks so much for any help you can give!
I believe the issue is the function scope, which is a common mistake.
The addEventListener method has no implied scope, so the functions will get called on window. If you output this in your console when those buttons are clicked, you will probably see Window. To solve this, you can:
Bind your methods (docs)
Example:
this.close1_btn.addEventListener("click", function (closebtn)
{
this.gotoAndPlay(1);
}.bind(this));
Use the CreateJS on shortcut, which takes a 3rd parameter (docs)
Example:
this.close1_btn.on("click", function (closebtn)
{
this.gotoAndPlay(1);
}, this);
One important note is that if you play frame 0 again, that frame script will run again, adding another listener to each button each time, resulting in the functions called multiple times when a button is clicked. I recommend something this this:
if (!this.inited) {
// Your code
this.inited = true;
}
Thanks for your response.
I am now using the code you provided:
this.stop();
if (!this.inited) {
// Your code
this.close1_btn.addEventListener("click", function (closebtn)
{
this.gotoAndPlay(1);
}.bind(this));
this.store1_btn.addEventListener("click", function (store1btn)
{
this.gotoAndStop(11);
}.bind(this));
this.inited = true;
}
However, I get this in the output
WARNINGS:
Frame numbers in EaselJS start at 0 instead of 1. For example, this affects gotoAndStop and gotoAndPlay calls. (5)
Content with both Bitmaps and Buttons may generate local security errors in some browsers if run from the local file system.
Any further advice you could give would be appreciated...
cheers for your continued assistance!
The preview doesn't work when it opens in my browser, is this just because I haven't exported it fully and hosted it online?
So I can ignore these errors?
^^ if that's all cleared up. Do you have recommended way to export and host it on a webpage?
Thanks again buddy, appreciate it!
I have this code in a Meteor.methods definition:
update_field: function(collection,document_id,field,value) {
obj = {};
obj[field] = value;
console.log(obj);
if (collection == 'clients') {
var Collection = Clients;
} else if(collection = 'sites') {
var Collection = Sites;
}
Collection.update(
{
_id: document_id
}, {
$set: obj
}, function(error,id) {
console.log(error,id);
return(error,id);
}
);
}
This method is called from several client-side helpers events, and updates the field as needed. But whenever it runs once, it never stops running. Sometimes it runs infinitely even when all the Meteor.call('update_field')s have been commented out. I have tried including a 'caller' parameter and adding that to all the possible calls to figure out why it keeps getting called to no avail. Any ideas why this is looping?
Edit: this runs 2,000/minute
Edit2: this is called in one of two ways: on a keyup code==13 (enter) in an appropriate field or a field blur. However, event when these calls are commented out, the issue persists.
Especially your second comment worries me:
However, even when these calls are commented out, the issue persists.
Then who is calling it? The behaviour you're describing points to some helper executing the method. The method changes some data, which re-executes the helper (reactivity) and we end up with a classic endless loop.
Check your entire source code for references to this method:
$ grep -r "update_field" *
Maybe you set a variable somehow and then use the variable to call the method. Also: Have you declared the method inside a Meteor.methods({ ... }) block?
I think the issue was that one of my methods blurred the input field but preventDefaulted. Then the blur handler was called and caused the loop from there. This is my first Meteor project, so I'm chalking this one up to not quite understanding the system sufficiently. I still find it strange that the method was getting called when the callers were commented out, but I'll figure that one out another day.
I am coding in ASP.NET MVC 5.2, and using jQuery as my primary script library. I am having a bit of a problem though, with the disparity between _Layout and views that use that layout.
Essentially, it goes like this
_Layout has some script that needs to run (initial wiring, progress bar, splash screen, etc)
Inheriting View has some script that needs to run (unique to that view)
_Layout has additional scripts that need to run after the view's unique scripts.
I have been trying a lot of ways to solve this, but it is actually proving to be a big problem. I have been frequently told that I should not create objects on the global namespace, so I am wondering if there are any other options to creating a script object that I can access in both views that isn't as damaging as global objects.
I have tried promises, and that is getting frustrating. I have tried events, and that doesn't really help because I cannot figure out what to attach the events to. I am told not to attach them to $(document), but that is really one of the only things that will be shared between the view and the layout.
I understand that global objects are not considered good in javascript, but at this point I'm not sure what other options I have to make sure things execute in the right order.
Update
The issue is more about "tooling" than it is about run time. It is true that when the actual view loads and runs, it is all pressed into one big happy page, and would work just fine. The issue is mostly that I have to split up the logic in the tooling (Visual Studio) to keep it from throwing errors and getting confused.
So I suppose it is more accurate to say it is a pseudo-problem.
I have attempted to split up the logic like this, but I think this is just another way of declaring a global object. I got the idea from the Q.js library.
Tasks.js
(function(definition) {
// assign the task system
tasks = definition();
})(function() {
var list = [];
function tasks() {
};
tasks.start = start;
tasks.enqueue = enqueue;
/*
* start the task queue.
*/
function start() {
// make sure to raise a started event for things that need
// to monitor it.
$(this).trigger("started");
};
function enqueue(f) {
// add the potential function to the queue to be processed later.
list.push(f);
$(this).trigger("enqueue", { item: f });
};
return tasks;
});
example usage
$(function(){
$(tasks).on("started", function(){
console.log("event called");
});
console.log("tasks", tasks);
tasks.start();
});
There are a number of ways you could go about this:
Use RequireJs to define Tasks as a module, then:
require(['tasks'], function(tasks){
$(tasks).on("started", function(){
console.log("event called");
});
console.log("tasks", tasks);
tasks.start();
});
Use a global object, but namespace it:
Ciel = Ciel || {};
Ciel.tasks = Ciel.tasks || function(){
var list = [];
...
};
Tie your data to a specific dom element:
<div class="ciel-tasks"></div>
...
$(function() { $('.ciel-tasks').each(function() {
var tasks = $(this);
...
});
It's not really clear what you're describing. From JavaScript's perspective there's no such thing as "_Layout" and "Inheriting View." There's only the resulting DOM delivered to the browser. Any JavaScript code within that DOM can operate on anything else in that DOM. So I'm not sure what any of this has to do with global namespace, events, $(document), etc. Perhaps you're overcomplicating the issue by assuming disparity between your views when, client side, no such disparity exists?
_Layout has additional scripts that need to run after the view's unique scripts.
This sounds like it's just a matter of providing callbacks for operations so that they internally execute in the correct order. For example, if the desired order is:
Layout executes initializeLayout()
View executes initializeView()
Layout executes completeLayout()
Then you can pass these to one another as callbacks and the functions can internally execute those callbacks. So in your Layout you might have something like this at the very top (such as in the header, as long as it's before the view is rendered):
<script type="text/javascript">
function initializeView(){} // placeholder for view-specific initialization
</script>
Then at the bottom with the rest of your scripts:
initializeLayout();
initializeView(completeLayout);
What this does is provide your views with an opportunity to overwrite that initializeView function. If the view defines its own function called initializeView then that one will be executed instead of the placeholder one defined in the layout (remembering that the layout and the view are all one page to JavaScript).
(This also assumes you've elsewhere defined a completeLayout function, since that's what you want to execute after the view is initialized.)
Then in your view you can define that overwriting function:
function initializeView(callback) {
// do some stuff...
if (typeof callback == 'function') {
callback();
}
}
That will execute your view initialization code and then when it's complete will invoke the callback which was provided by the layout, so the layout will then execute its post-view-initialization code. (Naturally, if any of this "initialization" code is asynchronous, you'll want to invoke callbacks in response to those asynchronous callbacks, etc.)
I'm displaying a series of images in a loop, and I'm trying to implement some sort of nudity filter so I'm using nude.js, a library that can somewhat detect nudity. Here's the code:
// we're inside a loop
$(".images").prepend($("<img>").attr({src: whatever, id: uniqueid}).load(function(e) {
nude.load(e.target.id);
nude.scan(function(result) { if (!result) $(e.target).detach(); });
});
However, it detaches all of the wrong images because nude.js is slow and it completes after the loop has gone on to the later iterations, detaching those images instead of the one it was working on.
I've tried using a function factory:
function generateCallback(arg) {
return function(result) { if (!result) $(arg).detach(); };
}
and
nude.scan( generateCallback(e.target) )
but the same thing happens.
What I want is a load event that will remove the image if it seems to contain nudity. How can I do this properly?
EDIT: nude.js works like this:
nude.load(imageid);
nude.scan(callback); // it'll pass true or false into the callback
another edit: accidentally omitted the id setting from the code I posted, but it was there in my real code, so I added it here.
I suspect the case here is that this kind of sequential processing won't work with nude.js.
Looking at the nude.js code, I think your problem is occurring in the call to nude.scan. nude.js has a variable that stores the function to invoke after the scan has completed. When calling nude.scan(callback), this variable is set to be callback.
From your PasteBin, it seems as though the callback gets assigned as expected on the first call, but on the second and subsequent calls, it gets replaced, hence why the second image is detached and not the first.
What happends to your script, is that the e var is global to the function and so after each loop it gets replaced with the new one. So when the first image is scanned, e already became the event of the second image, which get detached.
To solve your problem, use closures. If you want to know more about closures, have a look here.
Otherway, here's the solution to your problem :
$(".images").prepend($("<img>").attr({src: whatever, id: uniqueid}).load(function(e) {
(function(e) {
nude.load(e.target.id);
nude.scan(function(result) { if (!result) $(e.target).detach(); });
}) (e);
});
EDIT: AS nick_w said, there is var that contains the callback and probably gets replaced each time so this is why it isn't the right picture getting detached. You will probably have to modify the script yourself
I am learning javascript, and am trying to adjust the following:
$('#myform').change(function() {
if ($('#sv_I4b').attr('checked')||$('#sv_I4c').attr('checked')){
$('#sv_I5').removeClass('hidden');
} else {
$('#sv_I5').addClass('hidden');
}
});
To be a a function with a name that I can call on different events, such as page load etc.
I don't yet fully understand each element, but I know that:
if ($('#sv_I4b').attr('checked')||$('#sv_I4c').attr('checked')){
$('#sv_I5').removeClass('hidden');
} else {
$('#sv_I5').addClass('hidden');
}
is the core "logic" of the function: if (condition) {then this} else {that}
and more or less understand what is happening there. Which leaves the bounding javascript (is there better terminology than that?):
$('#myform').change(function() {...});
My Questions (are the following true etc):
The dollar I think denotes that it is jQuery
The id my form obviously
pertains the script to events within that form (namespace?)
.change seems to be, a trigger that listens to ... any change taking place
within #myform? so every time a change happens within #myform this
runs? That seems inefficient
function() I don't yet understand what
an anonymous or empty function does, just defines what is contained
in {} as a function?
My goal: to be able to have something like
function myfunction()
{
if ($('#sv_I4b').attr('checked')||$('#sv_I4c').attr('checked')){
$('#sv_I5').removeClass('hidden');
} else {
$('#sv_I5').addClass('hidden');
}
}
and then
$(function() {myfunction});
so I can call that function on page load, but I don't wan't to loose the functionality the .change syntax is providing me (that it changes as the user interacts with the elements on the page also.
Apologies for the general and cumbersome levels of ignorance
You guessed how to define the function correctly — that is,
function myfunction()
{
if ($('#sv_I4b').attr('checked')||$('#sv_I4c').attr('checked')){
$('#sv_I5').removeClass('hidden');
} else {
$('#sv_I5').addClass('hidden');
}
}
works just fine. However, this:
$(function() {myfunction});
Should be written as:
$(myfunction); // Run on page load.
$('#myform').change(myfunction); // ...and also run it when the form changes.
However, that second line won't actually work until the page has loaded unless the form exists at the time the script runs, so you may want to change it to this:
$(function() { // On page load, run this anonymous function:
myfunction(); // Run the function now (where now, at this point, is page load).
$('#myform').change(myfunction); // ...as well as when the form changes.
});
$ is shorthand notation for jQuery, and essentially namespaces any functions to the jQuery framework.
my_form is a DOM selector. $('#my_form') wraps the matched DOM element up as a jQuery object, adding all sorts of useful methods and properties.
.change() is an event listener which, as you guessed, watches for change events on that jQuery object. It is a little inefficient - take a look .on() instead.
the most useful behaviour an anonymous function (closure) is to create private scope, something that javascript doesn't otherwise provide.