Javascript: Function inside object not working - javascript

I am trying to create a controller in Javascript, which will respond to button clicks and change the view accordingly.
I have a function which works that looks like this:
document.getElementById("reset").onclick = function () {
//do something
};
However, when I try to put the function in a controller object, I get an "unexpected token" error:
var controller = {
this.reset = document.getElementById("reset").onclick = function () {
//do something
};
}
I'm not sure about 2 things:
How to fix this error? (I know its due to scope, but don't know how to fix it in a way that still follows MVC patterns)
Generally speaking, is this a good way to go about creating a controller object? (I'm new to the MVC model, and don't know if I'm following best practices.)
Thanks.

The error is due to that the object cant be declared like that, there are different ways to do it:
var obj1 = {
a : function() {
console.log('obj1');
}
};
var obj2 = function() {
var b = function() {
console.log('obj2');
};
return {
a: b
}
};
var obj3 = function() {
this.a = function() {
console.log('obj3');
}
};
And then use it.
obj1.a; //prints obj1
obj2().a; //prints obj2
new obj3().a; //prints obj3.
About how to structure your objects is opinion based, but i like to do it like this.
var Controller = function() {
this.attachEvents = function() {
document.getElementById("reset").onclick = reset;
}
var reset = function() {
console.log('reset');
};
}
new Controller().attachEvents();
another option is..
var Controller = function() {
this.reset = function() {
console.log('reset');
};
}
var controller = new Controller();
document.getElementById("reset").onclick = controller.reset;

This is not a valid Javascript object structure, but you can do it in following if it works for you
var controller = {
reset : function () {
document.getElementById("reset").onclick = function(){
//do your work here
}
}
}
Logic is completely on you/developer how he/she wants to handle things.
or you can do the binding thing outside, like,
var controller = {
reset : function () {
//what to do to rsest
}
}
and then, bind it elsewhere
//when to run reset method
document.getElementById("reset").onclick = controller.reset;

Related

UnCaught TypeError - Nested objects in Javascript? Why is this not allowed? Object literal notation works

Playing around with some JS tests and I'm trying to instantiate some nested objects in my v namespace. As you'll see below, ClassA and ClassB work as expected. When I try and nest some objects under another property (myCustomProperty) I start running into issues! Could someone explain?
Below is the original code:
var v = (v) ? v : {};
v.someClassA = (function() {
this.hello = function() {
console.log("Class A Hello!");
}
});
v.someClassB = (function() {
this.hello = function() {
console.log("Class B Hello!");
}
});
// this all works!
var myClassA = new v.someClassA();
var myClassB = new v.someClassB();
v.myCustomProperty = (function() {
function someClassC() {
this.hello = function() {
console.log('C');
}
}
function someClassD() {
this.hello = function() {
console.log('D');
}
}
return {
someClassC: someClassC,
someClassD: someClassD
}
});
// Uncaught TypeError: v.myCustomProperty.someClassC is not a function! Why?
var myClassC = new v.myCustomProperty.someClassC();
var myClassD = new v.myCustomProperty.someClassD();
myClassA.hello();
myClassB.hello();
myClassC.hello();
myClassD.hello();
If I change my declaration of v.myCustomProperty to use object literal notation, then it ALL WORKS! :
v.myCustomProperty = {
someClassC: function() {
this.hello = function() {
console.log('C');
}
},
someClassD: function() {
this.hello = function() {
console.log('D');
}
}
}
I guess my question really is how would I make this work using the notation in my original snippet? Possible? Horrible practice to do it that way?
Thanks!
v.myCustomProperty is a function that returns an object. You have to call the function first:
new (v.myCustomProperty().someClassC)();
// ^^
Otherwise, v.myCustomProperty.someClassC() tries to access the property someClassC of the function, and we all know (hopefully) that functions don't have such a property.
Or maybe you intended to execute the function immediately and assign the object to myCustomProperty?
v.myCustomProperty = (function() {
// ...
}()); // <- call function

Extend the properties returned by a function?

I'm a JS beginner. I have defined a function on my Backbone model as follows.
myFunction: function () {
return {
firstAttr: this.model.get('value-attribute')
};
}
It is available to me as this.myFunction.
From somewhere else in the code, I want to extend this.myFunction to return another attribute. In other words, I'd like it to return a dict with two attributes: { firstAttr: 'something', secondAttr: true }.
How can I do this?
I've tried:
this.myFunction().secondAttr = true;
but I know that's the wrong thing to do.
Assuming your model prototype looks like
var MyModel = Backbone.Model.extend({
myFunction: function () {
return {
// I assume you work directly on a model
// the principle would be the same with a wrapper object
firstAttr: this.get('value-attribute')
};
}
});
you can either mask your method on a model by model basis like this:
var m = new MyModel({'value-attribute': 'attr, the first'});
console.log(m.myFunction());
m.myFunction = function () {
var res = MyModel.prototype.myFunction.call(this);
res.secondAttr = true;
return res;
};
console.log(m.myFunction());
See http://jsfiddle.net/V8zt2/ for a demo
Or dynamically modify your prototype to alter all instances :
var f = MyModel.prototype.myFunction;
MyModel.prototype.myFunction = function () {
var res = f.call(this);
res.secondAttr = true;
return res;
};
var m = new MyModel({'value-attribute': 'attr, the first'});
console.log(m.myFunction());
http://jsfiddle.net/V8zt2/1/
How about modifying your myFunction to :
myFunction : function () {
var i,
obj = {};
for (i=0; i< arguments.length;i++){
obj['attribute'+(i+1)] = this.model.get(arguments[i]);
}
return obj;
}
This way you can send keys of model, that you want to be in the returned object as arguments to myFunction.

TypeError: Object is undefined

In a code below:
var FilledObjectArray = function() {
this.filledObject = {};
};
FilledObjectArray.prototype = {
fill: function() {
this.filledObject["one"] = 1;
}
};
var SomeClass = function() {
this.something = new FilledObjectArray();
};
SomeClass.prototype = {
showContents: function() {
this.something.fill();
for (key in this.something) {
$("#some-div").append(this.something[key]);
}
}
};
$(document).ready(function() {
var s = new SomeClass();
$(".bla").each(function() {
$(this).click(function() {
s.showContents();
});
});
});
I'm getting this error in Firebug console:
TypeError: this.filledObject is undefined
this.filledObject["one"] = 1;
What I'm doing wrong here? From what I understand object is properly initialized and value assigning is correct. I'm testing this in Firefox 18.0.2 version and Chrome 25.
I think this should solve your problem
this.something.fill.call(this.something);
I found this issue with the existing code and have created a proposed solution, however I'm not exactly clear on your intent so it may be a little different than your needs, please modify as needed.
The Issue
The main issue stems from the FilledObjectArray object. This object's prototype is assigned a function fill and then assigned a property one of type int with a value of 1. So remember this object has two properties, one a function one an int.
So when you execute this code...
for (key in this.something) {
$("#some-div").append(this.something[key]); //Item 1
}
Two iterations of the loop occur, once for the function fill and once for the property one. The issue occurs on the iteration for the fill key, since this.something[key] is passed to the append(), which cann accept functions, causing jQuery to trigger the function. When this occurs, within the execution context of the fill function, this is assigned to #some-div, which does not have a filledObject property, causing the TypeError to be thrown. I have commented on some of this below:
var FilledObjectArray = function() {
this.filledObject = {}; //Fill is an object
};
FilledObjectArray.prototype = {
fill: function() {
this.filledObject["one"] = 1;
}
};
var SomeClass = function() {
this.something = new FilledObjectArray();
};
SomeClass.prototype = {
showContents: function() {
this.something.fill();
for (key in this.something) {
$("#some-div").append(this.something[key]); //The fill function is called here
}
}
};
$(document).ready(function() {
var s = new SomeClass();
$(".bla").each(function() {
$(this).click(function() {
s.showContents();
});
});
});
Proposed Solution
var FilledObjectArray = function() {
this.filledObject = [];
};
FilledObjectArray.prototype.fill = function(){
console.log(this);
this.filledObject[0] = 1;
};
var SomeClass = function() {
this.something = new FilledObjectArray();
};
SomeClass.prototype = {
showContents: function() {
this.something.fill();
for (var x = 0; x < this.something.filledObject.length; x++){
$("#some-div").append(this.something.filledObject[x]);
}
}
};
$(document).ready(function() {
var s = new SomeClass();
$(".bla").each(function() {
$(this).click(function() {
s.showContents();
});
});
});
i think you looking for this:
for (key in this.something) {
if(this.something.hasOwnProperty(key)){
$("#some-div").append(JSON.stringify(this.something[key]));
}
}
jsbin
you need use hasOwnProperty to iterate over the properties of an object without executing on inherit properties.
I feel a bit dumb right now but here is the solution to this:
SomeClass.prototype = {
showContents: function() {
this.something.fill();
for (key in this.something.filledObject) {
if (this.something.filledObject.hasOwnProperty(key)) {
$("#some-div").append(this.something.filledObject[key]);
}
}
}
};
I was trying to access object itself (this.something) instead of object property (this.something.filledObject)

JS turning a function into an object without using "return" in the function expression

i have seen in a framework (came across it once, and never again) where the developer defines a module like this:
core.module.define('module_name',function(){
//module tasks up here
this.init = function(){
//stuff done when module is initialized
}
});
since i never saw the framework again, i tried to build my own version of it and copying most of it's aspects - especially how the code looked like. i tried to do it, but i can't seem to call the module's init() because the callback is still a function and not an object. that's why i added return this
//my version
mycore.module.define('module_name',function(){
//module tasks up here
this.init = function(){
//stuff done when module is initialized
}
//i don't remember seeing this:
return this;
});
in mycore, i call the module this way (with the return this in the module definition):
var moduleDefinition = modules[moduleName].definition; //the callback
var module = moduleDefinition();
module.init();
how do i turn the callback function into an object but preserve the way it is defined (without the return this in the definition of the callback)?
you have to use:
var module = new moduleDefinition();
and then you're going to get an object.
Oh, and maybe you want to declare init as this:
this.init = function() {
Cheers.
How about something like this (I can only assume what mycore looks like):
mycore = {
module: {
definitions: {},
define: function(name, Module) {
this.definitions[name] = new Module();
this.definitions[name].init();
}
}
};
mycore.module.define('module_name', function () {
// module tasks up here
this.init = function () {
// init tasks here
console.log('init has been called');
};
});
I don't know what framework you're using or what requirements it places on you, but Javascript alone doesn't require a function to return anything, even a function that defines an object. For example:
function car(color) {
this.myColor = color;
this.getColor = function() {
return this.myColor;
}
//note: no return from this function
}
var redCar = new car('red');
var blueCar = new car('blue');
alert(redCar.getColor()); //alerts "red"
alert(blueCar.getColor()); //alerts "blue"
One more alternative http://jsfiddle.net/pWryb/
function module(core){this.core = core;}
function Core(){
this.module = new module(this);
}
Core.prototype.modules = {};
module.prototype.define = function(name, func){
this.core.modules[name] = new func();
this.core.modules[name].name = name;
this.core.modules[name].init();
// or
return this.core.modules[name];
}
var myCore = new Core();
var myModule = myCore.module.define('messageMaker', function(){
this.init = function(){
console.log("initializing " + this.name);
}
})
myModule.init();

Is it possible to append functions to a JS class that have access to the class's private variables?

I have an existing class I need to convert so I can append functions like my_class.prototype.my_funcs.afucntion = function(){ alert(private_var);} after the main object definition. What's the best/easiest method for converting an existing class to use this method? Currently I have a JavaScript object constructed like this:
var my_class = function (){
var private_var = '';
var private_int = 0
var private_var2 = '';
[...]
var private_func1 = function(id) {
return document.getElementById(id);
};
var private_func2 = function(id) {
alert(id);
};
return{
public_func1: function(){
},
my_funcs: {
do_this: function{
},
do_that: function(){
}
}
}
}();
Unfortunately, currently, I need to dynamically add functions and methods to this object with PHP based on user selected settings, there could be no functions added or 50. This is making adding features very complicated because to add a my_class.my_funcs.afunction(); function, I have to add a PHP call inside the JS file so it can access the private variables, and it just makes everything so messy.
I want to be able to use the prototype method so I can clean out all of the PHP calls inside the main JS file.
Try declaring your "Class" like this:
var MyClass = function () {
// Private variables and functions
var privateVar = '',
privateNum = 0,
privateVar2 = '',
privateFn = function (arg) {
return arg + privateNum;
};
// Public variables and functions
this.publicVar = '';
this.publicNum = 0;
this.publicVar2 = '';
this.publicFn = function () {
return 'foo';
};
this.publicObject = {
'property': 'value',
'fn': function () {
return 'bar';
}
};
};
You can augment this object by adding properties to its prototype (but they won't be accessible unless you create an instance of this class)
MyClass.prototype.aFunction = function (arg1, arg2) {
return arg1 + arg2 + this.publicNum;
// Has access to public members of the current instance
};
Helpful?
Edit: Make sure you create an instance of MyClass or nothing will work properly.
// Correct
var instance = new MyClass();
instance.publicFn(); //-> 'foo'
// Incorrect
MyClass.publicFn(); //-> TypeError
Okay, so the way you're constructing a class is different than what I usually do, but I was able to get the below working:
var my_class = function() {
var fn = function() {
this.do_this = function() { alert("do this"); }
this.do_that = function() { alert("do that"); }
}
return {
public_func1: function() { alert("public func1"); },
fn: fn,
my_funcs: new fn()
}
}
var instance = new my_class();
instance.fn.prototype.do_something_else = function() {
alert("doing something else");
}
instance.my_funcs.do_something_else();
As to what's happening [Edited]:
I changed your my_funcs object to a private method 'fn'
I passed a reference to it to a similar name 'fn' in the return object instance so that you can prototype it.
I made my_funcs an instance of the private member fn so that it will be able to execute all of the fn methods
Hope it helps, - Kevin
Maybe I'm missing what it is you're trying to do, but can't you just assign the prototype to the instance once you create it? So, first create your prototype object:
proto = function(){
var proto_func = function() {
return 'new proto func';
};
return {proto_func: proto_func};
}();
Then use it:
instance = new my_class();
instance.prototype = proto;
alert(instance.prototype.proto_func());

Categories

Resources