I typically use the below design pattern to create jQuery plugins (http://jsbin.com/vegevido/1/).
For this one, I wish to add a utility method which will not be applied to elements like normal jQuery plugins, but could be used by the parent script.
As shown below, I have added the utility method multiply which is accessed by the parent script using $('#elem').makeRed('multiply',5,3).
Is this how I should be implementing this? It seems like it would be better to access this method using something like myPlugin.multiple(5,3) as it has nothing to do with #elem.
Thanks
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
<style type="text/css">
</style>
<script type="text/javascript">
(function($){
var defaults = {};
var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options);
return this.each(function () {
$(this).css('color', 'red');
});
},
makeBlue : function () {
$(this).css('color', 'blue');
},
multiply : function (x,y) {
return x*y;
},
destroy : function () {
return this.each(function () {});
}
};
$.fn.makeRed = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.makeRed' );
}
};
}(jQuery));
$(function(){
var myPlugin=$('#elem').makeRed();
$('#makeBlue').click(function() {$('#elem').makeRed('makeBlue');});
$('#multiply').click(function() {
console.log(myPlugin);
alert($('#elem').makeRed('multiply',5,3));
});
});
</script>
</head>
<body>
<div id="elem">Some Text</div>
<button id="makeBlue">makeBlue</button>
<button id="multiply">multiply</button>
</body>
</html>
One common pattern is to add it to the plugin definition like
$.makeRed = {
multiply: function (x, y) {
return x * y;
}
}
Demo: Fiddle
This is how jQuery UI exposes utility methods like $.datepicker.formatDate( format, date, settings )
Related
How to addEventListener which will be triggered only one time + passing arguments to it?
function () {
var params = ...
elem.addEventListener('load', function(event, params) {
elem.removeEventListner('load', ...);
do_something(params)
}
}
when using addEventListener, you can provide a config object as a second argument, where you can specify that it should run once (like the code below). Regarding passing an extra argument to your event callback, you can use the method bind by providing the context and the extra argument
var button = document.querySelector('#btn');
button.addEventListener('click', function (params, ev) {
console.log(params);
}.bind(button, { name: 'test'}), {
once: true
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button id="btn">click</button>
</body>
</html>
If you name your anonymous function you can reference it inside:
function () {
var params = ...
elem.addEventListener('load', function callback(event, params) {
elem.removeEventListner('load', callback);
do_something(params)
}
}
It wont leak to the global scope so you can name all of your 'one-time' events callback.
The removeEventListener method requires you to specify which function you're removing. That means you need a reference to that function so you can pass it to both addEventListener and removeEventListener. Something like this:
function bindListener(elem, params) {
var listener = function() {
do_something(params);
elem.removeEventListener('load', listener);
}
elem.addEventListener('load',listener);
}
I am working with Backbone and Jquery. I have a button inside a template and for some reason that button does not trigger any click events. I've tried all the suggested solutions on stackoverflow but none of them worked for me. Below is the code Im working with - I've made it as short as possible.
Any ideas why the YES button does not work?
EditView.html
<section id="EditView">
<button id="button-yes">YES</button>
</section>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<header id="header"></header>
<div id="content"><div id="content-inner"></div></div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"> </script>
<script type="text/javascript">
var myapp = myapp || {};
myapp.EditView = Backbone.View.extend({
events: {
'click #button-yes': 'buttonClickHandler'
},
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template());
return this; // support chaining
},
buttonClickHandler : function(event){
alert( $(event.currentTarget).text() );
return false;
}
});
myapp.utils = {
loadTemplates: function(views, callback) {
var deferreds = [];
$.each(views, function(index, view) {
if (myapp[view]) {
deferreds.push($.get(view + '.html', function(data) {
myapp[view].prototype.template = _.template(data);
}));
} else {
console.log(view + " not found");
}
});
$.when.apply(null, deferreds).done(callback);
}
};
myapp.AppRouter = Backbone.Router.extend({
routes: {
"": "add"
},
initialize: function() {
this.add;
},
add: function() {
if (!this.editView) {
this.editView = new myapp.EditView({el: $("#content-inner")});
};
$('#content').html(this.editView.el);
}
});
myapp.utils.loadTemplates([ 'EditView'], function() {
myapp.router = new myapp.AppRouter();
Backbone.history.start();
});
</script>
</body>
</html>
I'm not entirely sure why you're having a problem, seems to be some race condition where the element doesn't exist when backbone attempts to bind the event to it. It's an interesting case. Anyway, you can solve it for now by adding
myapp.router.editView.delegateEvents();
after Backbone.history.start();
I have to manage the callback when calling a service function from a controller. My idea is to wrap the service functionality in a promise but then I can't reference the service function from the controller directly. Instead I have to create another function to handle the view events.
function exampleSrv($q) {
this.exampleFn = function() {
var q = $q.defer();
// Do something
q.resolve();
return q.promise;
};
}
function exampleCtrl(exampleSrv) {
this.exampleFn = exampleSrv.exampleFn;
/* This works but I want to avoid this if possible
this.clickHandler = function() {
this.exampleFn()
.then(function() {
console.log('yay');
})
};
*/
/* And instead do something like this but as a reference not as a call
this.exampleFn()
.then(function() {
console.log('yay');
})
*/
}
Is there a better approach to do this?
Example:
http://plnkr.co/edit/jg5yoC?p=info
In short, no, there's no better approach to this. In fact this is the advised manner to tackle such problems.
Actually, you can try something like this: (I am having plunker issues otherwise would have created one)
// Example Service
function exampleSrv($q) {
this.exampleFn = function() {
var q = $q.defer();
// Do something
q.resolve();
return q.promise.then(function() {
return {
"data": "12345"
};
});
};
}
// Example Controller
function exampleCtrl(exampleSrv) {
var ctrl = this;
exampleSrv.exampleFn().then(function(data){
ctrl.exampleFn = data;
});
/* This works but I want to avoid this
this.clickHandler = function() {
this.exampleFn()
.then(function() {
console.log('yay');
})
};
*/
/* And instead do something like this
this.exampleFn()
.then(function() {
console.log('yay');
})
*/
}
angular.module('example', [])
.service('exampleSrv', exampleSrv)
.controller('exampleCtrl', exampleCtrl);
Then in the HTML markup, you can do this:
<!DOCTYPE html>
<html ng-app="example">
<head>
<script data-require="angular.js#1.2.14" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="exampleCtrl as example">
<!-- bind value directly from service -->
{{example.exampleFn}}
</body>
</html>
This way, you don't need an extra controller function and can take service data directly to your markup. Hopefully this is what you were looking for. Good luck.
I've been struggling with exactly what the correct syntax is to make methods available on an object with a plugin. Here's the basic framework:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery -->
<script type="text/javascript" src="http://goo.gl/XQPhA"></script>
<script type="text/javascript">
(function($) {
$.test = function(el, options) {
this.whiten = function() {
$(this).css('background-color', options.bg);
}
};
$.test.settings = {
bg: 'white'
};
$.fn.test = function(options) {
options = $.extend(options, $.test.settings);
return this.each(function() {
$.test(this, options);
});
};
})(jQuery);
$(document).ready(function() {
$('#list').test().css('background-color', 'wheat');
$('#go').click(function() {
$('#list').whiten();
});
});
</script>
</head>
<body>
<button id="go">whiten</button>
<ul id="list">
<li>Aloe</li>
<li>Bergamot</li>
<li>Calendula</li>
<li>Damiana</li>
<li>Elderflower</li>
<li>Feverfew</li>
</ul>
</body>
</html>
and I guess what I'm not sure about is how to make the function assignment. this inside of $.test will refer to the jQuery object wrapped around my list so I would have thought that this.myMethod = function() { would have worked but it doesn't. $(this) would be a double wrapper, el is my list (and I don't want to assign the method directly to the object since I wouldn't be able to call it like this: $('#list').whiten()), and $(el) would be the same as $(this)... so how is this done?
-- update --
I've created a [jsfiddle] to play with the problem
-- update --
I also did try placing the method in the $.fn.test function but to no avail
Try this:
$.fn.test = function(options) {
options = $.extend(options, $.test.settings);
var self = this;
return this.each(function() {
$.test(self, options);
});
};
after much wailing and gnashing of teeth, I figured it out. I'm not sure I understand why it works that way but for now I'm just happy it does!
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://goo.gl/XQPhA"></script>
<script type="text/javascript">
(function($) {
$.test = {
bg: 'white'
};
$.fn.test = function(options) {
options = $.extend({}, $.test, options);
this.whiten = function() {
$(this).css('background-color', options.bg);
};
return this.each(function() {
$.fn.test(options);
});
};
})(jQuery);
$(document).ready(function() {
$('#list').test().css('background-color', 'wheat');
$('#go').click(function() {
$('#list').whiten();
});
});
</script>
</head>
<body>
<button id="go">whiten</button>
<ul id="list">
<li>Aloe</li>
<li>Bergamot</li>
<li>Calendula</li>
<li>Damiana</li>
<li>Elderflower</li>
<li>Feverfew</li>
</ul>
</body>
</html>
I have this little jQuery plugin:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
(function($){
$.fn.foo = function(options){
var options = $.extend({
text: "Foo!",
}, options
);
this.prepend(
$("<span></span>").text(options.text)
).css({color: "white", backgroundColor: "black"});
return this;
};
})(jQuery);
$(function(){
$("div").foo().foo({text: "Bar!"}).css({border: "1px solid red"});
});
//--></script>
</head>
<body>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
Now I want to improve it so you are able to control where the text gets inserted by means of providing a callback function:
$(function(){
var optionsFoo = {
text: "Foo!",
insertionCallback: $.append
}
var optionsBar = {
text: "Bar!",
insertionCallback: $.prepend
}
$("div").foo(optionsFoo).foo(optionsBar).css({border: "1px solid red"});
});
(Please remember this is just sample code. I want to learn a technique rather than fix an issue.)
Can I pass a jQuery method as an argument and use it inside the plugin in the middle of a chain? If so, what's the syntax? If not, what's the recommended alternative?
Update: myprogress so far
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
(function($){
$.fn.foo = function(options){
var options = $.extend({
text: "Foo!",
insertionCallback: $.append
}, options
);
options.insertionCallback.call(this, // options.insertionCallback is undefined
$("<span></span>").text(options.text)
).css({color: "white", backgroundColor: "black"});
return this;
};
})(jQuery);
$(function(){
var optionsFoo = {
text: "Foo!",
insertionCallback: $.append
}
var optionsBar = {
text: "Bar!",
insertionCallback: $.prepend
}
$("div").foo(optionsFoo).foo(optionsBar).css({border: "1px solid red"});
});
//--></script>
</head>
<body>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
Sure you can, JavaScript is really dynamic:
this.prepend(
$("<span></span>").text(options.text)
).css({color: "white", backgroundColor: "black"});
You can replace the native call to this.prepend() with the jQuery function you pass in the options object as a parameter.
Since most jQuery methods behave on a current set of elements (the this object in your plugin) you need to use apply or call to make it work. This way you can call the options.insertionCallback function with the current this object as its context.
Something like:
options.insertionCallback.call(this, // pass the current context to the jQuery function
$("<span></span>").text(options.text)
).css({color: "white", backgroundColor: "black"});
Edit
However you can't access jQuery methods directly from the $ namespace, you need a constructed jQuery object to access its methods, or simply use $.fn.functionName as Nick Craver pointed out.
alert($.prepend); // won't alert the function
alert($.fn.prepend); // will alert the function
extend it like so:
(function($){
$.fn.foo = function(options){
var options = $.extend({
text: "Foo!",
cb: null
}, options
);
if($.isFunction(options.cb)){
// optimal also pass parameters for that callback
options.cb.apply(this, []);
}
this.prepend(
$("<span></span>").text(options.text)
).css({color: "white", backgroundColor: "black"});
return this;
};
})(jQuery);
I don't really understand what you mean with
Can I pass a jQuery method as an argument and use it inside the plugin in the middle of a chain?
Why would you want to pass a jQuery method ? it's already in there so you can just call it on any jQuery object.
You can also do this string based to keep it simple, like this:
(function($){
$.fn.foo = function(options){
var options = $.extend({
text: "Foo!",
insertionCallback: "append"
}, options
);
return this[options.insertionCallback]($("<span></span>").text(options.text))
.css({color: "white", backgroundColor: "black"});
};
})(jQuery);
Then your call looks like this:
$(function(){
var optionsFoo = {
text: "Foo!",
insertionCallback: "append"
}
var optionsBar = {
text: "Bar!",
insertionCallback: "prepend"
}
$("div").foo(optionsFoo).foo(optionsBar).css({border: "1px solid red"});
});
You can test it here, this would allow you to use append, prepend, html and text, giving you a few options to set the content. In this case we're just taking advantage of JavaScript being a dynamic language, where this.prepend(something) is equal to this["prepend"](something).
Not an answer to your question, but the recommended style is:
<script type="text/javascript">
//this
jQuery(function($) {
//... stuff using the jQuery lib, using the $
});
//not this
$(function() {
//...
});
//or this
(function($) {
//...
})(jQuery);
</script>