0

I have a function that is working and looks like this:

var $$ = function(selector, context) {
    context = context || document;
    var elements = context.querySelectorAll(selector);
    return Array.prototype.slice.call(elements);
}

// My function
var myFunction = function() {
    $$( '.my-selector' ).forEach( function( element ) {
        element.addEventListener('click', function(e){
            console.log('Do something');
        });
    });
}

I would prefer it looks more like jQuery:

// My function
var myFunction = function() {
    $('.my-selector').click(function(e) {
        console.log('Do something');
    });
}

I can't figure out how to do that. Any ideas?

(I want my code to be independent of frameworks so I don't want jQuery)

1 Answer 1

1

Solution1: with your own wrapper: Fiddler link

var $$ = function(selector, context) {
    context = context || document;
    var elements = context.querySelectorAll(selector);    
    var wrapper = function(elem){
      var element = elem;
      this.click = function(cb){
      element.forEach(function(el){
          el.addEventListener('click', function(e){
            cb.apply(element,[e]);
          });
      });   
      };
    };

    return new wrapper(Array.prototype.slice.call(elements));
}


$$("#test").click(function(e){
 console.log("Do something:"+e.type);
});

Solution 2 directly binding to native element: Fiddler link

var $$ = function(selector, context) {
    context = context || document;
    var elements = Array.prototype.slice.call(context.querySelectorAll(selector));    
     elements.click = function(cb){
        elements.forEach(function(el){
            el.addEventListener('click', function(e){
              cb.apply(elements,[e]);
            });
        });     
      };

    return elements;   
}

$$("#test").click(function(e){
 console.log("Do something:"+e.type);
});
Sign up to request clarification or add additional context in comments.

4 Comments

Which of the solutions would you have used? The last one seems shorter so I would probably use that one.
2nd solution is same as jquery coz you can access the element. In 1st solution you cant access the element but bind to the nested functions. I would go for 2nd one if i want it to be more like jquery.
@Jens did it helped you?
Then I will try out the second one soon and accept your solution if it works like expected. Thank you so much so far!

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.