Javascript: Function inside object not working -
i trying create controller in javascript, respond button clicks , change view accordingly.
i have function works looks this:
document.getelementbyid("reset").onclick = function () { //do };
however, when try put function in controller object, "unexpected token" error:
var controller = { this.reset = document.getelementbyid("reset").onclick = function () { //do }; }
i'm not sure 2 things:
- how fix error? (i know due scope, don't know how fix in way still follows mvc patterns)
- generally speaking, way go creating controller object? (i'm new mvc model, , don't know if i'm following best practices.)
thanks.
the error due object cant declared that, there different ways it:
var obj1 = { : 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 use it.
obj1.a; //prints obj1 obj2().a; //prints obj2 new obj3().a; //prints obj3.
about how structure objects opinion based, 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;
Comments
Post a Comment