3

I'm wondering how to setup a shorthand function for a shorthand selector in javascript. I apologise if that isn't the correct termonolgy.

Example:

var abc = function (selector) {
  return document.querySelector(selector);
};

Allows you to:

var temp = abc('#someID').value;

What I'm wondering is how do you go about creating a custom .something (in a similar fashion to how jQuery have .val)?

For example calling:

abc('#someID').doSomething;

The the doSomething command allowing you to update the value (or pull it back) in a similar fashion to .val etc.

Thank you in advance.

0

3 Answers 3

3

Well, this is a very nice JS code-design question.

Let's try to create a simple jQuery implementation. For this, we should first scope things up.

  1. jQuery function is a wrapper. It will hold a reference to the node in the DOM, and it will provide an array functions that will "operate" on the node.
  2. Most of the functions (setters, for being more specific) should return a pointer to the wrapper itself, so you can chain operations.

You can define the wapper first, by defining your function.

// Here we define the constructor.
var q = function(selector){
    this._node = document.querySelector(selector);

    // Add more private stuff here if you like
}; 

//Now we can add functionality to the function prototype.
q.prototype.hide = function(){
    this._node.style.visibility = 'hidden';        
    return this;
};    

q.prototype.show = function(){
   this._node.style.visibility = 'visible';  
   return this;
};

q.prototype.val = function(){
   return this._node.value;
};

q.prototype.click = function(callback){
   this._node.onclick = callback;
   return this;
};

// This is just for not having to call new every-time we want a new instance
var $q = function(selector){
   return new q(selector);
};

Now let's play a bit

<label for="name"> Hey I'm a text box</label>
<input id="name" value="" />
<button id="clickMe"> Click me </button>

We will attach a click handler to the button, when the user clicks, we display the value that the textbox contains, then we hide the text box. All in a single line (chained commands).

$q('#clickMe').click(function(){
    alert($q('#name').hide().val());
});

See JsFiddle https://jsfiddle.net/4Lfangj4/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. This worked and was well explained. Thank you for your time.
3

To make that, you must return an object (easiest solution) or extend the prototype (advanced solution).

Returning an object

You can return the doSomething() method:

var abc = function (selector) {
  return {
        doSomething: function() {caller()},
        dom: document.querySelector(selector);
  }
};

And it works:

var temp = abc("#someID").dom.value;
var doSome = abc("#someID").doSomething();

Extending prototype

You can add a function to the object prototype:

var abc = function(sel){
     return document.querySelector(sel);
}
abc.prototype.doSomething = function() {
    caller();
};

And it works

var temp = new abc("#someID");
temp.doSomething(); //doSomething() method
temp.value; // value attribute of element

2 Comments

Using your prototype example. If I use abc("#someID").doSomething('hello'); I get a javascript error saying the function does not exist? Thank you for your reply.
Yeah, it's because the returning value in the constructor. This is a simple example to show you how to make it in two different ways, but I see that you accept other answer, more complete. In that answer you can see how to instantiate the dom element and then play with it with the methods. The example is exactly the same, but my code is only an example to show how to make, not a functional example. If you want that I explain more this answer, tell me and I try it.
0

Jquery keeps your selection in an internal property and decorates that property with methods that can help with is DOM presence.

Almost every time it returns the same object so you can chain method calls.

The point is that you cannot avoid keeping a reference to the selected DOM element and the decoration part

A simple example about selection and manipulating the DOM element note here i store a reference to document.querySelector and document.querySelectorAll which are pretty much as good as jquery selection mechanism (Sizzle)

var MyWrapper = (function(){
  var $ = document.querySelector.bind(document);
  var $$ = document.querySelectorAll.bind(document);
  var slice = Array.prototype.slice;
  var selection;

  var that = {
    select: select,
    remove: remove,
    html: html
  };

  function select(selector){
    selection = $(selector);
    return that;
  }

  function remove(){
    selection.parentNode.removeChild(selection);
    return undefined;
  }

  function html(htmlstring){
    if(typeof htmlstring == 'undefined'){
      return selection.innerHTML;
    } else {
      selection.innerHTML = htmlstring;
      return that;
    }
  }

  return that;
}())

of course jQuery is a much complex and sophisticated library for all kind of use cases but the above code can get you started

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.