How do I Apply chaining method on javascript document.createElement - javascript

I would like to create a jQuery type chaining on an element created using javascript's document.createElement(). The following code is generating an error "Cannot call method 'appendChild' of undefined" whenever I try to run my "append" method on a parent object that was defined by my function. Any help or suggestions are appreciated.
this.el = (function () {
function _el() {
var self = this,
ele;
this.add = function (tag) {
ele = document.createElement(tag);
return this;
},
this.byId = function (id) {
ele = document.getElementById(id);
return this;
},
this.byClass = function (cl) {
ele = document.getElementsByClassName(cl);
return this;
},
this.id = function (name) {
ele.id = name;
return this;
},
this.cl = function (name) {
ele.className = name;
return this;
},
this.css = function (style) {
_this.setCSS(ele, style);
return this;
},
this.html = function (str) {
ele.innerHTML = str;
return this;
},
this.append = function (parent) {
if (parent.nodeType === 1) {
parent.appendChild(ele);
}
console.log(ele);
console.log(ele.nodeType);
return this;
};
return this;
}
return new _el();
}());
This is how I use the function in my code. The first use works while the second one does not. It has something to do with the type of object being returned by my function but I am not sure how to correct.
var dialog = hlp.el.add("div").cl("alphaDialog").append(document.body);
var top = hlp.el.add("div").append(dialog);

this.append function returns this object which holds _ele js object. We have to return our HTML element ele. In this.append we return ele;
this.el = (function () {
function _el() {
var self = this,
ele;
this.add = function (tag) {
ele = document.createElement(tag);
return this;
},
this.byId = function (id) {
ele = document.getElementById(id);
return this;
},
this.byClass = function (cl) {
ele = document.getElementsByClassName(cl);
return this;
},
this.id = function (name) {
ele.id = name;
return this;
},
this.cl = function (name) {
ele.className = name;
return this;
},
this.css = function (style) {
_this.setCSS(ele, style);
return this;
},
this.html = function (str) {
ele.innerHTML = str;
return this;
},
this.append = function (parent) {
if (parent.nodeType === 1) {
parent.appendChild(ele);
}
console.log(ele);
console.log(ele.nodeType);
//return this; // this holds javascript object, not element
return ele; // return our ele variable which holds the element
// this.append() is the end of the chain
};
return this;
}
return new _el();
}());

Related

Namespace With New Instance On Each Call

I'm trying to create something similar to d3(ex: d3.select()) but much more simple and I need to have a new instance each time I call the namespace function. Is this possible and/or am I approaching this wrong?
var dom = new function () {
var Element = null;
this.select = function (query) {
Element = document.querySelector(query);
return this;
};
this.append = function (elem) {
Element.append(elem);
return this;
};
};
Desired use
var bodyelement = dom.select("body");
var p = dom.select("p");
You need to run some code each time you use the dom object. So if the dom object was a function, you could call it to get a new instance.
var dom = function () {
var Element = null;
var newdom = {};
newdom.select = function (query) {
Element = document.querySelector(query);
return this;
};
newdom.append = function (elem) {
Element.append(elem);
return this;
};
return newdom;
};
console.log(dom() === dom(), "(false means the instances are different)");
var dom = new function () {
var Element = null;
this.select = function (query) {
Element = document.querySelector(query);
return this;
};
this.append = function (elem) {
Element.append(elem);
return this;
};
// add a way of accessing the resulting Element
this.element = function() { return Element; }
};
console.log(dom.select("body").element());
console.log(dom.select("p").element());
<p>blah</p>

Can't have access to a variable using call in Javascript

I'm studying Javascript and learning how to use call. I created this script and I don't know why I can't have access to this variable Time.
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {});
var myNewObj = new MyObject.Runner(1000); myNewObj.newTest('1', function() {
console.log(this.time) //output: undefined
});
So how can I get time value inside newTest function?
Issue is in newTest function
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
Here this is pointing to test and not Runner. You will have to save context in a variable and then set it in call.
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
.call + self
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
var self = this;
var test = function() {
return execute.call(self);
}
myFunctionArray.push(test);
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
.bind
As commented, you can even use .bind
var MyObject;
(function(MyObject) {
var Runner = (function() {
function Runner(time) {
this.time = time;
}
var myFunctionArray = [];
Runner.prototype.execute = function() {
myFunctionArray[0]();
}
Runner.prototype.newTest = function(index, execute) {
myFunctionArray.push(execute.bind(this));
}
return Runner;
})();
MyObject.Runner = Runner;
})(MyObject || (MyObject = {}));
var myNewObj = new MyObject.Runner(1000);
myNewObj.newTest('1', function() {
console.log(this, this.time) //output: undefined
});
myNewObj.execute()
When you declare your Runner function, you've actually declared a function that takes no arguments that then itself declares a function called Runner that takes one argument.
Actually In this code snippet :
Runner.prototype.newTest = function(index, execute) {
var test = function() {
return execute.call(this);
}
myFunctionArray.push(test);
}
this will reference to test variable (as per constructor invocation pattern)
So, to pass right variable cache the value of this in another variable and then pass that to function.

Protractor page object and element.all

I want my element.all() to return children with prototyped methods.
here's my code so far:
el.tags = function() {
var el = element.all(by.css('.tags > span'));
// return el;
return el.map(function(tag) {
tag.name = function() {
return tag.element(by.binding('tag.name')).getText()
}
tag.count = function() {
var text = tag.element(by.binding('tag.count')).getText()
return _.parseInt(text);
}
return tag;
});
}
the idea being once I call tags() the children have my prototyped methods immediately.
var tags = tags().filter(function(tag) {
return tag.name() === "foobar";
});
thanks!

Javascript select element in library

I am working on a javascript library that will work like this: tex("element").print("hi"). Here is the code:
(function (window) {
var regex = {
Id : /^[#]\w+$/,
Class : /^[.]\w+$/,
Tag : /^\w+$/,
validSelector : /^([#]\w+|[.]\w+|\w+)$/
},
tex = function(selector){
//only some of the functions need to select an element
//EX:
// style: tex(selector).style(style);
//one that would not need a selector is the random number function:
// tex().random(from,to);
if (selector){
if (typeof selector === 'string'){
var valid = regex.validSelector.test(selector);
if( valid ){
if(regex.Id.test(selector)){
this = document.getElementById(selector);
}
if(regex.Class.test(selector)){
this = document.getElementByClass(selector);
}
if(regex.Tag.test(selector)){
this = document.getElementByTagName(selector);
}
}
}else if(typeof selector === 'object'){
this = selector;
}
//this = document.querySelector(selector);
// I could make a selector engine byt I only need basic css selectors.
}
};
tex.prototype = {
dit : function(){
this.innerHTML = 'Hi?!?!?!'
}
};
window.tex = tex;
})(window);
When I try to run the code I get an error that says, "Left side of argument is not a reference" referring to this = document.getElementById(selector);
Does anyone know what is wrong with my code?
Because you can not set this.
To do something that you are after, you just return this.
without using a prototype
var foo = function( selector ) {
this.print = function () {
console.group("in print");
console.log(this.elements[0].innerHTML);
console.groupEnd("in print");
return this;
}
this.printAll = function () {
console.group("in printAll");
for (var i=0; i<this.elements.length; i++) {
console.log(this.elements[i].innerHTML);
}
console.groupEnd("in printAll");
return this;
}
this.elements = document.querySelectorAll( selector );
return this;
}
console.group("id");
foo("#foofoo").print();
console.groupEnd("id");
console.group("class");
foo(".bar").printAll().print();
console.groupEnd("class");
JSFiddle
Basic example with prototype
(function () {
var basic = function (selector) {
this.elements = document.querySelectorAll(selector);
return this;
}
basic.prototype.print = function () {
console.group("in print");
console.log(this.elements[0].innerHTML);
console.groupEnd("in print");
return this;
}
basic.prototype.printAll = function () {
console.group("in printAll");
for (var i = 0; i < this.elements.length; i++) {
console.log(this.elements[i].innerHTML);
}
console.groupEnd("in printAll");
return this;
}
var foo = function (selector) {
return new basic(selector);
}
window.foo = foo;
})();
console.group("id");
foo("#foofoo").print();
console.groupEnd("id");
console.group("class");
foo(".bar").printAll().print();
console.groupEnd("class");
JSFiddle

Javascript Library Extend way

I'm writing my own JavaScript library. How can I do for extend my object in this way?
_.mymethod();
Here's my code:
(function (window, undefined) {
"use strict";
var emptyArray = [];
function _(id) {
return new _.fd.init(id);
}
_.fd = _.prototype = {
init: function (selector) {
this.el = document.getElementById(sel);
return this;
},
replaceText: function (text) {
this.el.innerHTML = text;
return this;
},
changeTextColor: function (color) {
this.el.style.color = color;
return this;
}
};
_.fd.init.prototype = _.fd;
_.extend = function (target) {};
_.extend({});
window._ = _;
}(window));
The point is, how to extend for using method like
_.method();

Categories

Resources