I have created my jQuery custom plugin as;
(function($){
$.fn.userForm = function(){
var element = this;
var UserDataObj = {
name:"John",
email:"john#example.com",
phone:"9999999999",
desc:"some description"
}
this.supports_html5_storage = function()
{
};
this.saveFormData = function(param)
{
}
if (this.supports_html5_storage())
{
}
else
{
}
};
})(jQuery);
Now I am trying to call a method within my plug in as;
var myPlugin = new $.fn.userForm();
myPlugin.saveFormData(".formFieldUserData");
For some reason, the code breaks in IE while executing
var myPlugin = new $.fn.userForm();
How do I fix this issue?
Related
I am developing a JQuery plugin. I need to use OOP inside my plugin. However, the class not working as I expected. When I initiate a new instance of the class, it is only the first line of its code that is executing. What is wrong with this code and how to execute a constructor of this class on initiation?
(function ($) {
var FunClass;
FunClass = function () {
console.log("FunGlobal");
function FunClass() {
console.log("FunConstructor");
}
FunClass.prototype.letsFun = function () {
console.log("FunMethod");
}
}();
$.fn.fun = function () {
var funClass;
return this.each(function () {
funClass = new FunClass();
funClass.letsFun();
});
};
}(jQuery));
Here is the console output: Console Output
Thanks for help.
Seems you've forgot to return FunClass:
(function($) {
var FunClass;
FunClass = (function() {
console.log("FunGlobal");
function FunClass() {
console.log("FunConstructor");
}
FunClass.prototype.letsFun = function() {
console.log("FunMethod");
}
return FunClass; // you missed this line
})();
$.fn.fun = function() {
var funClass;
return this.each(function() {
funClass = new FunClass();
funClass.letsFun();
});
};
}(jQuery));
// Usage
$(function() {
$('body').fun();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Trying to convert a lot of jQuery and JS to an Angular controller so that it works the "NG" way. I've looked at the docs and it looks like I can setup a document ready function in Angular using something like angular.element(document).ready to initialize the jQuery variable. What I am confused on is "this" and it's place in the angular world. Anyone have an idea of where to start?
Here is a Pen of what I am trying to accomplish:
CodePen
And I know that there is ng-show/ng-hide and that ngAria shows up around 1.3 but I am just trying to grasp the basis for converting a lot of jQuery to angular.
Here is my current script:
$(document).ready(function() {
var hs1 = new hideShow('open1', 'close1');
var hs2 = new hideShow('open2', 'close2');
var hs3 = new hideShow('open3', 'close3');
var hs4 = new hideShow('open4', 'close4');
});
function hideShow(toggleID, closeID) {
this.$toggle = $('#' + toggleID);
this.$close = $('#' + closeID);
this.$region = $('#' + this.$toggle.attr('aria-controls'));
this.keys = {
enter: 13,
space: 32
};
this.toggleSpeed = 100;
this.bindHandlers();
}
hideShow.prototype.bindHandlers = function() {
var thisObj = this;
this.$toggle.click(function(e) {
thisObj.toggleRegion();
e.stopPropagation();
return false;
});
this.$close.click(function(e) {
thisObj.hideRegion();
e.stopPropagation();
return false;
});
}
hideShow.prototype.hideRegion = function() {
this.$region.hide().attr('aria-expanded', 'false');
this.$toggle.find('span').html('Show');
this.$toggle.focus();
}
hideShow.prototype.toggleRegion = function() {
var thisObj = this;
this.$region.slideToggle(this.toggleSpeed, function() {
if ($(this).attr('aria-expanded') == 'false') { // region is collapsed
$(this).attr('aria-expanded', 'true');
$(this).focus();
thisObj.$toggle.find('span').html('Hide');
} else {
$(this).attr('aria-expanded', 'false');
thisObj.$toggle.find('span').html('Show');
}
});
}
Any suggestions or examples are appreciated.
I need to know how is possible to get a plugin variable outside the plugin, to test it with some test framework.
So this is my simplified plugin:
(function ($) {
$.fn.extend({
myPlugin: function (argumentOptions) {
var defaults = {
image: 'img/default.png',
};
this.textSend = '';
var options = $.extend(defaults, argumentOptions);
var globalHere = this;
return this.each(function () {
obj.mouseup(function(e) {
globalHere.textSend = 'test';
});
});
}
});
})(jQuery);
I need to the variable this.textSend outside the plugin.
I have tried in this way:
$(document).ready(function(){
var testfield = $('.txt');
testfield.myPlugin({
image:"../img/twitter.png"
});
testfield.focus();
testfield.trigger($.Event( "mouseup"));
console.log($.fn.myPlugin.textSend);
});
but the console.log return me undefined
How can i get that variable outside?
Thanks
You will want to make sure you are returning this like so:
(function($) {
$.fn.extend({
myPlugin: function(argumentOptions) {
var self = this;
self.textSend = 'something';
self.inc = 0;
self.mouseup(function(e) {
self.textSend = 'new thing #' + self.inc;
self.inc++;
});
return self;
}
});
})(jQuery);
var instantiated = $('button').myPlugin({});
$('input').val(instantiated.textSend);
$('button').click(function(e) {
$('input').val(instantiated.textSend);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>Current textSend:</label>
<input />
<br/>
<button>Change textSend</button>
Hopefully will get you on the right track.
Update
Try new code.
You can store it inside the closed scope you created around your plugin and expose it through another function. Of course it'll need some refactoring, but this is the general idea:
(function ($) {
var whateverNameYouWant; //here
$.fn.extend({
myPlugin: function (argumentOptions) {
var defaults = {
image: 'img/default.png',
};
this.textSend = '';
whateverNameYouWant = this.textSend; //here
var options = $.extend(defaults, argumentOptions);
var globalHere = this;
return this.each(function () {
obj.mouseup(function(e) {
globalHere.textSend = 'test';
whateverNameYouWant = this.textSend; //here
});
});
}
});
$.extend({
getWhateverNameYouWant: function() {
return whateverNameYouWant;
}
})
})(jQuery);
var value = $.getWhateverNameYouWant();
At line console.log($.fn.myPlugin.textSend);
use testfield.textSend . now it has become proprty of selector via myplugin.
I'm currently working on counting the number of opened tabs on my application. but my problem is it seems that my script won't detect events onload. Here is my code.
I'm using HTML5 web storage and native js. I'm not using jQuery to understand more on native js.
(function(w) {
function Tabz(win, key) {
this.name = '';
this.storageKey = key;
if(win.name != '')
this.name = win.name;
else {
var windowArr = JSON.parse(localStorage.getItem(key)) || [];
this.name = "tabz_"+ windowArr.length;
win.name = this.name;
windowArr.push(this.name);
localStorage.setItem(this.storageKey, JSON.stringify(windowArr) );
}
}
Tabz.prototype.getStorage = function() {
return localStorage.getItem(this.storageKey);
}
Tabz.prototype.removeWindow = function() {
//remove window function here
}
var newWindow = new Tabz(w, 'counter');
window.load = function() {
var count = JSON.parse(newWindow.getStorage()).length;
alert(count!); // this wont execute so that I can check the count.
}
})(window);
Your issue is on this line:
window.load = function() {
This will add a load property to the window, not add an event listener. I think you are looking for onload.
window.onload = function() {
Incidentally, using event properties is considered bad-practice. Using addEventListener would be better.
window.addEventListener("load", function(){
//Do stuff...
});
A bad title and this might not be the best way to do what I'm trying to do (still learning javascript) but I'm trying to wrap a object using a delegate. The object in this case is an XMLHttpRequest.
var wrapper = function() {
this._delegate = /* get the delegate */
this._delegate.onreadystatechange = function() {
wrapper.readyState = this.readyState;
/* stuff that synchronizes wrapper goes here */
if(wrapper.onreadystatechange) {
wrapper.onreadystatechange();
}
};
return this;
}
The above is a simplification but when problem is that when I add an onreadystatefunction to the wrapper object like:
wrapper.onreadystatechange = function() {alert("hi)};
and the wrapper._delegate.onreadystatechange function is called, wrapper.onreadystatechange is always undefined and the alert popup never comes up. I think I'm getting my scope stuff wrong but I'm not exactly sure how to fix this. Would appreciate other suggestions but I would also like to know how to fix what I'm doing wrong. Thanks!
EDIT
Yup it was an incomplete example. sorry about that. I realized after trying to rewrite it into a complete example what my cause my issue. It seems if I don't have the outer "WRAP_FUNCTION" then it will work fine. I had written something like
WRAP_FUNCTION = (function() {
var originalXMLHttpRequest = window.XMLHttpRequest;
var wrapper = function() {
if(wrapper.wrapped) {
this._delegate = new originalXMLHttpRequest;
} else {
this._delegate = new window.XMLHttpRequest
}
this._delegate.onreadystatechange = function() {
wrapper.readyState = this.readyState;
/* stuff that synchronizes wrapper goes here */
if(wrapper.onreadystatechange) {
wrapper.onreadystatechange();
}
};
return this;
};
wrapper.prototype.open = function(method, url, async) {
this._delegate.open(method, url, async);
}
wrapper.prototype.send = function() {
this._delegate.send();
}
wrapper.wrapped = true;
return wrapper;
}
window.XMLHttpRequest = WRAP_FUNCTION;
HTML code:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="xmlhttp.js"></script>
<script type="text/javascript">
(function() {
var test = new XMLHttpRequest();
test.open("GET", "xmlhttp.js", true);
test.onreadystatechange=function()
{
if (test.readyState==4 && test.status==200)
{
alert("yay");
}
};
test.send();
})();
</script>
</body>
</html>
Try this.
var wrapper = function() {
// in this time var wrapper not yet defined completly
// if you want use wrapper on the finction
// need to use this instead of wrapper
var self= this;
this._delegate = /* get the delegate */
this._delegate.onreadystatechange = function() {
//this means _delegate is in this time
//if you want to use this(wrapper)
//set the value out of function
//like var self= this
//wrapper.readyState = this.readyState;
self.readyState = this.readyState;
/* stuff that synchronizes wrapper goes here */
//if(wrapper.onreadystatechange) {
// wrapper.onreadystatechange();
//}
if(self.onreadystatechange) {
self.onreadystatechange();
}
};
return this;
}