using self executing function in javascript properly - javascript

I am trying to use the self-executing function with rails 6 but I have an error. I cannot figure out what is the issue
here is the code
../javascript/pack/show.js
var Show = (function(){
var init = function(){
alert("hello world!");
};
return{
init: init
};
})();
and this is the erb file
.....
<%=javascript_pack_tag 'show' %>
<script>
$(document).on('turbolinks:load', function() {
Show.init();
})
</script>
in the console it says
ReferenceError: Show is not defined when view the page
i cannot find the issue

Related

How to make function execute only once in JS / JQuery

i have a structure like this :
// App.js
var APP = {
viewIndex: function(){
EVT.doSomething();
},
// Another function below
}
// Event.js
var EVT = {
doSomething: function(){
deleteField();
function deleteField(){
$("body").on("click", "#btn", function(){
console.log("Clicked");
})
}
}
}
my project is SPA wannabe, so when i want to change the page, it must execute some function inside App.js, but my problem is, when i call APP.viewIndex() (when i go to Index, go back, and go to index again(without refreshing page) ), the function inside EVT -> doSomething() is execute twice, so i have no idea how to prevent it,
in my console i got this :
Clicked
Clicked
*sorry if my explanation is a bit complicated
hope you guys can help me out of this problem :D
thanks
Use a property to remember if you already called deleteField().
var EVT = {
didSomething: false,
doSomething: function(){
if (!this.didSomething) {
deleteField();
this.didSomething = true;
}
function deleteField(){
$("body").on("click", "#btn", function(){
console.log("Clicked");
})
}
}
}

Function from other file is not defined

I wrap by $(function) both files for running code when page is ready. But for some reasons calling function from first file in second file gives me error "ReferenceError: test is not defined".
First file:
$(function() {
function test() {
alert(1);
}
});
Second file:
$(function() {
test();
});
This is because JavaScript scope, you can avoid this by using Window global object.
Adding your variables to Window object will make them global, so you can access them from anywhere.
First file:
$(function() {
window.test = function () {
alert(1);
}
});
Second file:
$(function() {
test();
});

Does 'command' in Google Closure have the prototype?

I am using Google Closure and am trying to do something like below:
abc.edf.commands.showToast = function() {
abc.edf.commands.showToast.test(); // this works fine
this.test2(); // this will throw an error like:
// exception_logger.js:88 TypeError: this.test2 is not a function
};
abc.edf.commands.showToast.test = function() {
console.log('test');
};
abc.edf.commands.showToast.prototype.test2 = function() {
console.log('test2');
};
I think every object in JavaScript has 'prototype'. So is it because 'command' is not an object? Or I missed something else? Thanks :)
As Felix Kling commented you need to use new to create an object in order to use the test2 prototype function. Here is an example:
goog.provide('abc.edf.commands.showToast');
/** #constructor */
abc.edf.commands.showToast = function() {};
abc.edf.commands.showToast.test = function() {
console.log('test');
};
abc.edf.commands.showToast.prototype.test2 = function() {
console.log('test2');
};
abc.edf.commands.showToast.test(); // static class method
var foo = new abc.edf.commands.showToast();
foo.test2(); // instance method
You can try entering that code in the online closure compiler. Here is what it compiles to using simple compile:
var abc={edf:{}};
abc.edf.commands={};
abc.edf.commands.showToast=function(){};
abc.edf.commands.showToast.test=function(){console.log("test")};
abc.edf.commands.showToast.prototype.test2=function(){console.log("test2")};
abc.edf.commands.showToast.test();
var foo=new abc.edf.commands.showToast;
foo.test2();
Here is what it compiles to using advanced compile:
console.log("test");
console.log("test2");
To test, I saved the compiled code to a file "showToast.js" and made a simple html page that loads it:
<!doctype html>
<html>
<head>
</head>
<body>
<p>ShowToast Test</p>
<script src="showToast.js"></script>
</body>
</html>

How to get angular variable to javascript when using scope() method

This is how I get my input. sql table -> php slim -> angularjs -> website.
I need to GET a variable in javascript that php slim is returning to angular.
Right now I'm using this in $( document ).ready(function() {.
var $element = $('div[ng-show="game"]');
var scope = angular.element($element).scope();
console.log(scope);
It returns this in console.
Any ideas how to achieve this?
In your Angular controller just create your JQuery method there.
//Controller
function someController($scope) {
$scope.game = GetFromSlim();
$scope.yourMethod = function(){
$('#someDiv').innerHtml($scope.game.total_rating);
}
}
Then you can just call your method from the view using angular.
//View
<div ng-controller="someController" ng-app>
<div id="someDiv"></div>
<button ng-click="yourMethod()">Just do it</button>
</div>
Angular 2 or AngularJS 2 ++
Without scope method also can be passed as below. You have to write somecodes inside angular page(Declare, define and redefine) and some in javascript.
A. In angular (i used in common angular page) write below code
//Declare and Define of variables
environmentStringify = {
'project_url':'172.23.77.82:4200/myangularproject/',
'testMode':true
};
declare var environmentStringify: any;
environmentStringify = JSON.stringify(environment);
B. in html page (i used index.html inside head and script tags) write below codes
<script type="text/javascript">
var environmentStringify = "{{environmentStringify}}";
var environment = null;
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function setJSEnvironmentVariable(){
if(isJsonString(environmentStringify)){
environment = JSON.parse(environmentStringify);
} else {
setTimeout(function(){
setJSEnvironmentVariable();
}, 500);
}
}
setJSEnvironmentVariable();
</script>

jquery plugin Uncaught TypeError: object is not a function

I just created my first jQuery plugin , it is very simple it slideToggle two Divs , the code works fine and it do what i want , the problem is that i get an ERROR message at the console saying :
Uncaught TypeError: object is not a function
it refer to this line of code
})(jQuery);
CODE
$(function($) {
$.fn.toggleDiv = function(opt) {
var options = $.extend({}, $.fn.toggleDiv.objectOptions, opt);
return this.each(function() {
if (options.animation == true) {
$(this).slideToggle();
} else {
$(this).toggle();
}
});
};
$.fn.toggleDiv.objectOptions = {
animation: false
};
$("button").click(function() { $("#Div1, #Div2")
.toggleDiv({animation : fa}); return false; });
})(jQuery);
Does any one know what is that error and how can i fix it thanks
You either want to do
(function ($) { ... })(jQuery);
if you want your code to be run immediatly,
or
jQuery(function ($) { .... });
for your code to be run on document-ready.
You are referring to $("button"), and therefore need the document tree to be available. So use the second version. A even nicer solution would be to use the jQuery function "delegate", this would look something like this:
jQuery(function ($) {
$(document).delegate("button", "click", function (ev) { ... });
});

Categories

Resources