2

I have the following problem, I'm trying to make a small chained.

(function(window){
window.de=de={}

de.one=function(s){if(s){var y=document.getElementById(s); return y;} return this;}

de.two=function(s2){alert(s2); return this;}

})(window)

this is what I try to:

de.one("Id").two("Hello!");

but the console gives me this error:

TypeError: Object # has no method 'two'

1
  • You are returning y(which is the html element) not this Commented Jul 22, 2013 at 1:30

3 Answers 3

3

The console isn't lying. HTMLElement doesn't have a method named two, as that method belongs to window.de.

Don't modify host objects like HTMLElement by adding to their prototype. They aren't implemented in JavaScript.

Write a wrapper that contains your methods instead, sort of like jQuery:

(function(window) {
    var de = function(thing) {
        return new de.prototype.init(thing);
    };

    de.prototype = {
        constructor: de,

        init: function(thing) {
            this.thing = thing;
        },

        one: function(other) {
            return de(other);
        }
    };

    de.prototype.init.prototype = de.prototype;

    window.de = de;
})(window);

Now, you can do:

de('foo').one('bar').one('bar').one('baz')
Sign up to request clarification or add additional context in comments.

Comments

1

To give you an idea:

LIVE DEMO

(function(window){

var myLibrary = (function( s ) {
  var d = document,
      e = d.getElementById( s ),
      methods = {
        one : function(val){
            alert(val);
            return this; // maintain chainability
        }, 
        two : function(val){
            alert(val);
            return this; // maintain chainability
        },
        css : function( property, val){
            if(!val && typeof property == "object" ){ // styles in Object notation
                for(var key in property){
                    e.style[key] = property[key];
                }
            }else{ // Comma separated: property, value
                e.style[property] = val || undefined;
            }
            return this;    
        }
    };
    return methods;

});
window.myLibrary = window.de = myLibrary; // Make Window accept "de" as "myLib" alias.   

})(window);

de("Id").one("UGA!!!").two("yoo").css({color:"red", background:"gold"});

taking in consideration that you have something like:

 <div id="Id">Some element</div>

Comments

1

You can't do this, the problem is in de.one(), you have 2 different TYPES of return values.

"return y" and return "this". If you want to chain, you have to "this".

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.