var self = this?

Using instance methods as callbacks for event handlers changes the scope of this from “My instance” to “Whatever just called the callback”. So my code looks like this function MyObject() { this.doSomething = function() { … } var self = this $(‘#foobar’).bind(‘click’, function(){ self.doSomethng() // this.doSomething() would not work here }) } It works, but … Read more

Why does this UnboundLocalError occur (closure)? [duplicate]

This question already has answers here: How can I change a global variable from within a function? (8 answers) Using global variables in a function (24 answers) Closed 5 years ago. What am I doing wrong here? counter = 0 def increment(): counter += 1 increment() The above code throws an UnboundLocalError. 8 Answers 8

Access a variable outside the scope of a Handlebars.js each loop

I have a handlebars.js template, just like this: {{externalValue}} <select name=”test”> {{#each myCollection}} <option value=”{{id}}”>{{title}} {{externalValue}}</option> {{/each}} </select> And this is the generated output: myExternalValue <select name=”test”> <option value=”1″>First element </option> <option value=”2″>Second element </option> <option value=”3″>Third element </option> </select> As expected, I can access the id and title fields of every element of myCollection … Read more

Accessing class variables from a list comprehension in the class definition

How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3: class Foo: x = 5 y = [x for i in range(1)] Python 3.2 gives the error: NameError: global name ‘x’ is not defined Trying Foo.x doesn’t work either. … Read more

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

When I was studying for my undergraduate degree in EE, MATLAB required each function to be defined in its own file, even if it was a one-liner. I’m studying for a graduate degree now, and I have to write a project in MATLAB. Is this still a requirement for newer versions of MATLAB? If it … Read more

How do I pass the this context to a function?

I thought this would be something I could easily google, but maybe I’m not asking the right question… How do I set whatever “this” refers to in a given javascript function? for example, like with most of jQuery’s functions such as: $(selector).each(function() { //$(this) gives me access to whatever selector we’re on }); How do … Read more