Javascript Object Confusion - javascript

I've confused myself nicely here. My scenario is as follows:
function DesignPad() {
function EditBar() {
...
this.removeHandler = function() {
**// how do I call Dragger.removeAsset**
}
}
function Dragger(){
...
this.removeAsset = function() {}
}
this.init = function() {
this.editBar = new EditBar();
this.dragger = new Dragger();
}
}
var dp = new DesignPad();
...
I can't seem to call Dragger.RemoveAsset. I understand the why, my question is how do I call it?
I'm trying to keep like-things separated (e.g. Dragger / EditBar) but I seem to get all sorts of mixed up in my event handlers. Any suggestions, good reading materials, etc. on this stuff?

I found Douglas Crockford's Javascript to be the best introduction to JavaScript. Especialy videos for Yahoo, like: The JavaScript Programming Language where you can learn how exactly are objects created and inherited in JS.
Solution to you problem is:
function DesignPad() {
var that = this;
function EditBar() {
this.removeHandler = function() {
print("RemoveHandler");
that.dragger.removeAsset();
}
}
function Dragger() {
this.removeAsset = function() {
print("RemoveAsset");
}
}
this.init = function() {
this.editBar = new EditBar();
this.dragger = new Dragger();
}
}
var dp = new DesignPad();
dp.init();
dp.editBar.removeHandler();
But as others noticed you could refactor some things :).

To me it just looks like you should refactor that code to make it simpler.
I think that your issue comes from the fact that a nested function is private, so you can't access it from outside.

Is an instance of Dragger a 'property' of your DesignPad object? If so, you could pass a reference to that object into your removeHandler() method.

Try this:
function DesignPad() {
function EditBar(s) {
super = s;
this.removeHandler = function() {
alert('call 1');
super.dragger.removeAsset();
}
}
function Dragger(s){
super = s;
this.removeAsset = function() {
alert('call 2');
}
}
this.init = function() {
this.editBar = new EditBar(this);
this.dragger = new Dragger(this);
}
}
var dp = new DesignPad();
dp.init()
dp.editBar.removeHandler();
alert('end');

Related

javascript class with event methods

My goal is to make a class with some chained functions, but I'm stuck and hoping for some help. This is what I got:
robin = new batman("myiv");
var batman = (function() {
var me = this;
function batman(id){
me._id=id;
document.getElementById(id).addEventListener('mousemove', me.mouseMoving.bind(me),true);
}
this.mouseMoving = function(){
document.getElementById(me._id).style.background="orange";
}
return batman;
}
And this pseudo code is what I am aiming to get. Basically, pass in the ID of an element in my HTML and chain functions to it such as onclick etc, and whatever code inside there, runs. as in example, changing background colors.
Is it possible?
superman("mydiv"){
.onmouseover(){
document.getElementById(the_id).style.background="#ffffff";
},
.onmouseout(){
document.getElementById(the_id).style.background="#000000";
},
etc...
}
edit: updated with missing code: "return batman;"
You can do method chaining by returning the current object using this keyword
var YourClass = function () {
this.items = [];
this.push = function (item) {
if (arguments) {
this.items.push(item);
}
return this;
}
this.count = function () {
return this.items.length;
}
}
var obj = new YourClass();
obj.push(1).push(1);
console.log(obj.count())
Working sample
https://stackblitz.com/edit/method-chaining-example?file=index.js

How to structure a javascript class to use multiple sub-methods at once?

Let's say I have those three classes:
function Basket() {
this.catches = []
}
Basket.prototype.addCatch = function(catch) {
catches.push(catch)
}
function Pole() {
}
Pole.prototype.catchFish = function() {
return "fish"
}
function Fisherman() {
this.pole = new Pole()
this.basket = new Basket()
}
Now when I create a Fisherman I can catch a fish and put it into the basket.
Now I would like to do both in one call. The way I implemented it now is the following:
function Fisherman() {
this.pole = new Pole()
this.basket = new Basket()
this.utils = {}
this.utils.catchAndStore = function() {
let { pole, basket } = this
basket.addCatch(pole.catchFish())
}.bind(this)
}
I seems to work but does not feel quite right. What would be a good way to structure my class to achieve this goal? Or should this complexity be let out of this class?
just like this:
Fisherman.prototype.catchFish = function () {
if (!this.basket.addCatch || !this.pole.catchFish)
return console.log("Hey!I need correct tools!");
this.basket.addCatch(this.pole.catchFish());
}

How to implement sub function in JavaScript

How can I implement sub functions in JavaScript
callMethod(); // Works
callMethod.doThisWay(); // Still works
Sure you can :-)
Just write
const callMethod = function () {
// ...
};
callMethod.doThisWay = function () {
// ...
};
and you're done :-)
This also works:
var callMethod = function() {
this.doThisWay = function () {
alert('doThisWay');
}
alert('callMethod');
return this;
};
var a = new callMethod();
a.doThisWay();
there is some other ways to do this also.

using revealling moduler pattern for complex in javascript

I have a very complex class so i decided to break into sub modules and trying to use revealing modules pattern.
I have main class and decided to divide into smaller container function. but in current scenario
But i am not able to access any internal function from outside i.e callSearchResultWithCallBack using searchFinder.Search.callSearchResultWithCallBack(). which pattern should i use to keep this code clean as well have control to call internal function in sub module.
Thanks
var searchFinder;
function SearchFinder() {
me = this;
this.searchResult = null;
this.init = function() {
declareControls();
createAccordian();
addEvents();
fillControls();
var declareControls = function() {
this.SearchButtons = jQuery('.doSearch');
this.InputLocation = jQuery('#inputLocation');
this.InputDistanceWithIn = jQuery('#inputDistanceWithIn');
this.InputName = jQuery('#inputName');
}
var addEvents = function() {
me.SearchButtons.click(function() {
me.Search();
});
}
var fillControls = function() {
var getGetCategory = function() {
}
}
}
this.Search = function() {
var url = '';
var searchCriteria = {};
validateAndCreateCriteria();
callSearchResultWithCallBack();
function validateAndCreateCriteria() {
function validateAandGetCategory() {
if (SearchValidation.ValidateZipCode(me.InputLocation.val().trim())) {
searchCriteria.location = me.InputLocation.val().trim();
} else if (SearchValidation.ValidateCityState(me.InputLocation.val().trim())) {
searchCriteria.location = me.InputLocation.val().trim();
}
}
}
// need to access it outsite
function callSearchResultWithCallBack() {
me.searchResult(searchCriteria, SearchResultCallBack);
function SearchResultCallBack() {
}
}
}
}
jQuery(function() {
searchFinder = new SearchFinder();
searchFinder.init();
searchFinder.Search.callSearchResultWithCallBack();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
This code has multiple issues, first I will address the fact that for example declareControls is not executing. First declare the function than execute!
this.init = function() {
var declareControls = function() {
this.SearchButtons = jQuery('.doSearch');
this.InputLocation = jQuery('#inputLocation');
this.InputDistanceWithIn = jQuery('#inputDistanceWithIn');
this.InputName = jQuery('#inputName');
}
var addEvents = function() {
this.SearchButtons.click(function() {
me.Search();
});
}
var fillControls = function() {
var getGetCategory = function() {
}
}
declareControls();
//createAccordian(); //not defined
addEvents();
fillControls();
}
Now let's look at others problems that will arise.
the me object referring to this is in the scope of searchFinder and does not refer to the same this in the instance of searchFinder.
function jQuery can be replaced by the commonly used $.
searchFinder.Search.callSearchResultWithCallBack() this is never going to work. Since the Search function is an object and callSearchResultWithCallBack isn't a property of this function.
Solution; make it part of the prototype of Search.
Steps:
Move callSearchResultWithCallBack outside the search function.
Add prototype to Search function
Call function via prototype.
function callSearchResultWithCallBack() {
me.searchResult(searchCriteria, SearchResultCallBack);
function SearchResultCallBack() {
}
}
this.Search.prototype.callSearchResultWithCallBack = callSearchResultWithCallBack;
If you want to fire this function outside of search use this:
searchFinder.Search.prototype.callSearchResultWithCallBack();
Please remember that callSearchResultWithCallBack will throw an error because searchCriteria is undefined.
This fixes your problems for now, but this code has to be revised thoroughly. But this should get you started. http://ejohn.org/blog/simple-javascript-inheritance/

scratching my head over "this" statement in javascript. anyone help please

Ok after a day I managed to narrow down the problem to 2 lines of code. Maybe I am trying to use the this statement incorrectly.
function scheduleItemView(myId){
this.update = function(show){
document.getElementById(this.id+'-title').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-title-overlay').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-description').innerHTML = truncate(show.description,190);
document.getElementById(this.id+'-time-start').innerHTML = show.startTime;
document.getElementById(this.id+'-time-end').innerHTML = show.endTime;
};
this.id=myId;
return true;
}
function nowNextView(){
this.now = new scheduleItemView('now');
this.next = new scheduleItemView('next');
this.update = function(type,args){
var myshow=args[0];
// problem is below. I have to use the global name to access the update method.
myNowNextView.now.update(myshow.now);
myNowNextView.next.update(myshow.next);
// whereas what I want to do is reference them using the "this" command like below.
// this.now.update(myshow.now);
// this.next.update(myshow.next);
// the above doesnt work. The update method in scheduleItemView is not seen unless referenced globally
// BUT even more infuriating, this.now.id does return "now" so it can access the object, just not the method
// any ideas?
};
}
object is then instantiated with
var myNowNextView = new nowNextView();
and then I run the method:
myNowNextView.update(stuff);
I tried to describe the problem within the body of the program. No error in the code was thrown, and I had to do a try/catch before it grudgingly told me that it couldn't find the method.
Is the design flawed somehow? can I not do this?
Many thanks in advance,
Steve
function scheduleItemView(myId){
this.update = function(show){
document.getElementById(this.id+'-title').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-title-overlay').innerHTML = show.title +": "+ show.startDate;
document.getElementById(this.id+'-description').innerHTML = truncate(show.description,190);
document.getElementById(this.id+'-time-start').innerHTML = show.startTime;
document.getElementById(this.id+'-time-end').innerHTML = show.endTime;
};
this.id=myId;
}
function nowNextView(){
var myshow=args[0];
var scope = this;
this.now = new scheduleItemView('now');
this.next = new scheduleItemView('next');
this.update = function(type,args){
scope.now.update(myshow.now);
scope.next.update(myshow.next);
};
}
I think you could really benefit from studying closures a bit in javascript. It seems like you are trying to apply a traditional OO approach to js objects, and that won't give you the results you are expecting.
I would recommend reading over this post for an easy way to use closures:
http://howtonode.org/why-use-closure
Something like this:
<html>
<head>
<script type="text/javascript">
function createScheduleItemView(myId){
var _show = false
return {
setShow : function setShow(show) {
_show = show
},
update : function update(){
document.getElementById( myId +'-title').innerHTML = _show.title;
}
}
}
function createNowNextView(){
var _now = createScheduleItemView('now');
var _next = createScheduleItemView('next');
return {
publicVar : "Example",
update : function update(args) {
var myshow=args[0];
_now.setShow(myshow.now)
_now.update();
_next.setShow(myshow.next)
_next.update();
}
};
}
function runIt() {
nowNextView = createNowNextView()
args = []
showArgs = {
now : {title : "Beauty and the Beast"},
next : {title: "I did it myyyyyy way"}
}
args.push(showArgs)
nowNextView.update(args)
//Private variables can not be accessed
//console.log(nowNextView._now)
//undefined
//
//But anything you return in the object is public
//console.log(nowNextView.publicVar)
//Example
}
</script>
</head>
<body onload="runIt()">
<h3>Now Showing:</h3>
<p id="now-title"></p>
<h3>Up Next:</h3>
<p id="next-title"></p>
</body>
</html>

Categories

Resources