Is it inadvisable to add methods to a JQuery element?
eg:
var b = $("#uniqueID");
b.someMethod = function(){};
Update
Just to clarify, I am working on a JS-driven app that is binding JSON data to local JS objects that encapsulate the business logic for manipulating the actual underlying DOM elements. The objects currently store a reference to their associated HTML element/s. I was thinking that I could, in effect, merge a specific instance of a jquery element with it's logic by taking that reference add adding the methods required.
Well, there's nothing inherently wrong with it. It is, however, pretty pointless. For example:
$('body').someMethod = function(){};
console.log($('body').someMethod); // undefined
You are attaching the new function only to that selection, not to all selections of that element.
What you should do instead is to add a new function to jQuery.fn, which is a shortcut for jQuery.prototype:
jQuery.fn.someMethod = function() {
if (this[0].nodeName == 'body') {
// do your function
}
return this; // preserve chaining
};
The problem is that your function would be quite transient. A further requery and it will be gone. You can extend the jQuery object itself by $.fn.someMethod = function() {} and this method will be available for all queries.
$.fn.someMethod = function() {}
var b = $("body");
b.someMethod();
Or you can create a jQuery plugin. You can define a plugin this way:
$.fn.someMethod = function(options) {
# ...
});
Call it using $('body').someMethod();
Related
I need to develop a pure javascript plugin wich can be accessed like jquery typed plugins ( $('.pluginWrapper').pluginInit();
However i need to to use pure javascript and i was thinking maybe about 2 supported formats:
document.getElementById('pluginWrapper').pluginInit();
pluginInit(document.getElementById('pluginWrapper'));
I know that you have to do an IIFE to wrap it and call it via object methods but i do not know how i can bind that to an element.
I am mentioning that i am a begginer so please can someone please explain something about this. Cheers!
You would be safer developing a plugin interface that simply exposes plugins as functions which take an element as an argument.
function MyPlugin(element) {
// do stuff with element
element.setAttribute('data-plugin-id', 'pluginName');
}
The other approach involves extending Element.prototype. Which could potentially be a dangerous action in production software.
However, it is still possible.
Element.prototype.pluginInit = function() {
// the element is accessible as `this`
this.setAttribute('data-plugin-id', 'pluginName');
}
A function is easy for everyone to understand. Plugin writers don't have to understand any interfaces for creating and registering plugins, they just need to know that they should write functions that take elements as arguments.
There's a great talk from Rich Hickey (the creator of Clojure) called Simplicity Matters in which he stresses that the worst thing you can do is add additional complexity when simple solutions will do.
In this case, you don't need anything more complex than a function which takes an element as an argument.
If it is completely essential that you have control of the function, you could write a simple interface for registering and initiating plugins.
function Plugin(element) {
if(element === null) {
throw new TypeError("Element must not be null!");
}
// get all the plugin names from the store
var pluginNames = Object.keys(Plugin.store);
// make sure `this` is set to the element for each plugin
var availablePlugins = pluginNames.reduce(function(plugins, name) {
plugins[name] = Plugin.store[name].bind(element);
return plugins;
}, {});
// return an object containing all plugins
return availablePlugins;
}
// we'll store the plugins in this object
Plugin.store = {};
// we can register new plugins with this method
Plugin.register = function(name, pluginFn) {
Plugin.store[name] = pluginFn;
};
Which you could use like this.
Plugin.register('myPlugin', function() {
this.setAttribute('data-plugin-id', 'myPlugin');
});
Plugin(document.getElementById('pluginWrapper')).myPlugin();
If you want the plugin function to take a selector, the same way as jQuery, then you can use document.querySelectorAll inside your definition for Plugin.
function Plugin(selector) {
var element = document.querySelectorAll(selector);
if(element === null) {
throw new TypeError("Element must not be null!");
}
// get all the plugin names from the store
var pluginNames = Object.keys(Plugin.store);
// make sure `this` is set to the element for each plugin
var availablePlugins = pluginNames.reduce(function(plugins, name) {
plugins[name] = Plugin.store[name].bind(element);
return plugins;
}, {});
// return an object containing all plugins
return availablePlugins;
}
Then you would use it like this instead.
Plugin.register('myPlugin', function() {
this.setAttribute('data-plugin-id', 'myPlugin');
});
Plugin('#pluginWrapper').myPlugin();
I have a question regarding the structure of a jQuery plugin that I found.
For better understanding, here is a simplified example of the plugins structure:
// Regular constructor function
function MyPlugin() {
this.myValue = "My Value";
}
// Methods on the prototype
MyPlugin.prototype.showValue = function() {
alert($.myplug.getValue());
}
MyPlugin.prototype.getValue = function() {
return this.myValue;
}
// jQuery plugin
$.fn.myplug = function() {
// Why is is possible to access $.myplug here although it's not created yet?
return this.each(function() {
$(this).html($.myplug.getValue());
});
};
// Create new MyPlug instance
$.myplug = new MyPlugin();
// Calling the jQuery plugin on a DOM element
$('div').myplug();
For the most part, I get what is happening. The actual plugin logic seems to be written as a normal JavaScript "class".
This is followed by a jQuery plugin definition – I think, actually, some new method is added to jQuery's prototype. This is where things get tricky to me:
How is is possible to access the class instance inside the plugin, although the class is instantiated after the plugin definition? Is there a mechanism at work similar to variable hoisting?
In case you want to try something, here is a Fiddle of the example: http://jsfiddle.net/kq8ykkga/
$(this).html($.myplug.getValue()); isn't evaluated until you call $('selector').myplug(), executing the function body.
I'm working on a Single Page App and quite a few of the DOM node construction functions return a reference to the object they've created. Here's an example of what I mean:
if (!document.getElementById('playlistHeader')) {
appView.buildKit.playlist.headerWrap();
}
// construct element
var secondaryBtnsWrap = document.createElement("div");
secondaryBtnsWrap.id = "playlistSecondaryBtnWrap";
secondaryBtnsWrap.className = "clearright right";
// attach it
document.getElementById('playlistHeader').appendChild(secondaryBtnsWrap);
// return reference to dom node
return secondaryBtnsWrap;
I figured it would be redundant to destroy and recreate the node when changing between views, so I started working towards being able to wipe the content of some nodes (subsections of the site) by giving them a custom function that handles the wiping.
// build wipe function
secondaryBtnsWrap.wipe = function(){
// do custom wiping here
}
The idea is to "reset" parts of the UI and rebuild the differences between the views. For example, if there was a button that we'd need regardless, the wipe function won't delete it. That way it eliminates the extra legwork of creating the same element.
In some cases it's a lot easier to get a reference to a node and trigger the custom function attached, but I was wondering if its actually a good idea or if it just SEEMS like a good idea (but isn't).
TL;DR VERSION
Is it a good idea to give DOM nodes Javascript functions?
DOM Nodes are first-class objects. Nothing wrong with assigning them your own properties. Just don't try to overwrite any built-ins (except perhaps event handlers, but you should really be using attachEvent/addEventListener). In my opinion, it's one of the most convenient features of javascript in terms of user-interface development.
You could also build your page with a standard object which generates its own DOM nodes. You can attach event listeners which invoke functions on said object for interactivity. Use closures to reference the owner object. For instance:
function Foo() {
this.element = undefined;
this.createTextbox();
}
Foo.prototype.createTextbox = function() {
var $self = this;
this.element = document.createElement('input');
this.element.type = 'text';
this.element.addEventListener('change', function() {
$self.onChange.apply($self, arguments);
});
}
Foo.prototype.onChange = function() {
console.log(this.element.value);
}
Foo.prototype.Render = function(target) {
target = target || document.body;
target.appendChild(this.element);
}
var foo = new Foo();
foo.Render();
Both methods are equally valid, but I'd say the latter is probably more convenient when either the design or functionality needs to be significantly modified (rather than changing ids, classes, and layouts in both places, you only have to change them in one).
After discovering about Javascript namespaces, I tried to implement them but I run into a problem while trying to attach a namespace method to an element's onclick.
I used this method to wrap up my functions/methods/classes (a simplified concept, not my actual code):
;(function(window, undefined) {
//my namespace
var NS = {};
NS.test = {
f : function(param) {
alert(param);
}
}
NS.test.('test 2');
})(window);
Inside, everything works fine and "test 2" is prompted.
However, when I try to attach that function to a click event, by doing something like this:
<a href-"#" onclick="NS.test.f('test');">Click me!</a>
it doesn't work, just like it doesn't work when I call that function after the })(window); part.
I tried it calling it window.NS.test.f('test'); but with no effect.
How can I make an onclick event call my function?
I could attach an event listener inside my wrapper, like I do for other html elements with no difficulty, but it would be problematic in this case since I'm generating the links with javascript and I find it easier and simpler to just add onclick="doSomething" for all my links, instead of creating them, then cache them and add event listeners.
Call me lazy, but in this particular case I prefer to do
someDiv.innerHTML = my_Generated_Html_Code_With_OnClick;
instead of
//demo code, ignore the flaws and the fact it won't work on IE
someDiv.innerHTML = my_generated_Html_code;
myLink = document.getElementById(id);
myLink.addEventListener('mousedown', NS.test.f('test'));
I do not use any framework nor do I wish to, since I'm trying to get a better understanding of the so-called vanilla javascript first.
I set up a jsfiddle here.
P.S. I must admit I didn't understand namespaces completely so if I'm doing something wrong here or applying the concept in a way I am not supposed to, I would appreciate any tips or corrections
That's because NS is declared inside and hence only exists inside the function:
function(window, undefined) {
var NS = {};
// NS exists here ...
}
// ... but not here
If you want to make it available to the rest of the page, then you can do:
function(window, undefined) {
var NS = window.NS = {};
// NS and window.NS exist here ...
}
// ... and window.NS exists here.
I'm am trying to create a jQuery plugin that will add new namespace functions to the context object(s), while maintaining full chain-ability. I'm not sure if it's possible, but here's an example of what I have so far:
(function ($) {
var loadScreen = $('<div />').text('sup lol');
$.fn.someplugin = function (args) {
var args = args || {},
$this = this;
$this.append(loadScreen);
return {
'caption' : function (text) {
loadScreen.text(text);
return $this;
}
};
}
})(jQuery);
This works fine if I do $(document.body).someplugin().caption('hey how\'s it going?').css('background-color', '#000');
However I also need the ability to do $(document.body).someplugin().css('background-color', '#000').caption('hey how\'s it going?');
Since .someplugin() returns it's own object, rather than a jQuery object, it does not work as expected. I also need to be able to later on access .caption() by $(document.body). So for example if a variable is not set for the initial $(document.body).someplugin(). This means that somehow how .caption() is going to be set through $.fn.caption = function () ... just for the document.body object. This is the part which I'm not quite sure is possible. If not, then I guess I'll have to settle for requiring that a variable to be set, to maintain plugin functions chain-ability.
Here's an example code of what I expect:
$(document.body).someplugin().css('background-color', '#000');
$('.non-initialized').caption(); // Error, jQuery doesn't know what caption is
$(document.body).caption('done loading...');
Here's what I'm willing to settle for if that is not possible, or just very inefficient:
var $body = $(document.body).someplugin().css('background-color', '#000');
$('.non-initialized').caption(); // Error, jQuery doesn't know what caption is
$body.caption('done loading...');
The be jquery-chainable, a jQuery method MUST return a jQuery object or an object that supports all jQuery methods. You simply have to decide whether you want your plugin to be chainable for other jQuery methods or whether you want it to return your own data. You can't have both. Pick one.
In your code examples, you could just define more than one plugin method, .someplugin() and .caption(). jQuery does not have a means of implementing a jQuery plugin method that applies to one specific DOM object only. But, there is no harm in making the method available on all jQuery objects and you can only use it for the ones that it makes sense for.
I think you could use this:
(function ($) {
var loadScreen = $('<div />').text('sup lol');
$.fn.someplugin = function (args) {
var args = args || {},
$this = this;
$this.append(loadScreen);
return(this);
}
$.fn.caption = function (text) {
loadScreen.text(text);
return this;
}
})(jQuery);
$(document.body).someplugin().css('background-color', '#000');
$('.non-initialized').caption('whatever');
$(document.body).caption('done loading...');
If there's supposed to be some connection between the two .caption() calls, please explain that further because I don't follow that from your question.