Search Results

Search found 13794 results on 552 pages for 'variable scope'.

Page 5/552 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • php variable scope in oop

    - by mr o
    Hi, I wonder if anyone can help out here, I'm trying to understand how use an objects properties across multiple non class pages,but I can't seem to be able to get my head around everything i have tried so far. For example a class called person; class person { static $name; } but i have a number of different regular pages that want to utilize $name across the board. I have trying things like this; pageone.php include "person.php"; $names = new Person(); echo person::$name; names::$name='bob'; pagetwo.php include "person.php"; echo person::$name; I can work with classes to the extent I'm OK as long as I am creating new instances every page, but how can make the properties of one object available to all, like a shared variable ? Thanks

    Read the article

  • python variable scope

    - by Oscar Reyes
    I'm teaching my self python and I was translating some sample class Student: def __init__( self, name, a,b,c ): self.name = name self.a = a self.b = b self.c = c def average(self): return ( a+b+c ) / 3.0 Which is pretty much my intended class definition Later in the main method I create an instance and call it a if __name__ == "__main__" : a = Student( "Oscar", 10, 10, 10 ) That's how I find out that the variable a declared in main is available to the method average and that to make that method work , I have to type self.a + self.b + self.c instead What's the rationale of this? I found related questions, but I don't really know if they are about the same

    Read the article

  • Jquery post success variable scope

    - by minirobot
    Hi, I'm trying to return the ajax success array from one function to another. For some reason I don't seem to be able to pass the data stored in a variable in the success part of the ajax function into the parent function to return. Thanks so much for any assistance. Here's a simplified version of the code: // make json_to_return global var json_to_return; function loop_through_data(){ // call the load_days function and put its array data into days_array var days_data = load_days(03,2010); // I'd like to be able to iterate through days_data here // // } function load_days(selectedMonth, selectedYear){ $.ajax({ type: "POST", dataType: "json", url: "../includes/get_availability.php", data: "month=" + selectedMonth + "&year=" + selectedYear, success: function(available_json){ json_to_return = available_json; }, error: function(msg){ alert("error " + msg); } }); return json_to_return; }

    Read the article

  • Ruby IRB - Requires and Scope

    - by tyndall
    Trying to understand this problem I'm running into. I create file welcome.rb. The contents of this file: welcome_message = "hi there" I then launch an irb session. And type require 'welcome'. That works fine. Then I type: puts welcome_message I get the error message undefined local variable or method `welcome_message' for main:Object What is the best way to bring in predefined variables and have initialization work done when you require something into your irb session. Global variables didn't seem like the right path.

    Read the article

  • Javascript: Access the right scope "under" apply(...)

    - by Chau
    This is a very old problem, but I cannot seem to get my head around the other solutions presented here. I have an object function ObjA() { var a = 1; this.methodA = function() { alert(a); } } which is instantiated like var myObjA = new ObjA(); Later on, I assign my methodA as a handler function in an external Javascript Framework, which invokes it using the apply(...) method. When the external framework executes my methodA, this belongs to the framework function invoking my method. Since I cannot change how my method is called, how do I regain access to the private variable a? My research tells me, that closures might be what I'm looking for.

    Read the article

  • How do I scope variables properly in jQuery?

    - by safetycopy
    I'm working on a jQuery plugin, but am having some trouble getting my variables properly scoped. Here's an example from my code: (function($) { $.fn.ksana = function(userOptions) { var o = $.extend({}, $.fn.ksana.defaultOptions, userOptions); return this.each(function() { alert(rotate()); // o is not defined }); }; function rotate() { return Math.round(o.negRot + (Math.random() * (o.posRot - o.negRot))); }; $.fn.ksana.defaultOptions = { negRot: -20, posRot: 20 }; })(jQuery); I'm trying to get the private function rotate to be able to see the o variable, but it just keeps alerting 'o is not defined'. I'm not sure what I'm doing wrong.

    Read the article

  • Raphael Scope Drag n drop multiple paper instances

    - by donald
    I have two Raphael paper instances. In both I want to drag and drop an element (circle). It is important for me to assign both these circles the same id. I expected no problem, as both are in different paper instances and therefore in different scope. What happens is, that somehow both elements react, when I have clicked both elements at least once. If I however give these elements different IDs everything works fine (each element only calls its "start", "drag" and "up" function if draged around). Is this intended behaviour of Raphael and do I have to assign different IDs to the elements in the different paper instances? Hopefully not and you can point me to the right direction :-) Thanks a lot for your Help in advance, Here comes the code: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>DragNDrop</title> <script src="raphael-min.js"></script> </head> <body> <h1>Paper1</h1> <div id="divPaper1" style ="height: 150px; width: 300px; border:thin solid red"></div> <h1>Paper2</h1> <div id="divPaper2" style ="height: 150px; width: 300px; border:thin solid red"></div> <script> start1 = function () { console.log("start1"); } drag1 = function () { console.log("move1"); } up1 = function () { console.log("up1"); } start2 = function () { console.log("start2"); } drag2 = function () { console.log("move2"); } up2 = function () { console.log("up2"); } var paper1 = Raphael("divPaper1", "100%", "100%"); var circle1 = paper1.circle(40, 40, 30); circle1.attr("fill", "yellow"); circle1.id = "circle"; //both circles get the same id circle1.drag(drag1, start1, up1); paper2 = Raphael("divPaper2", "100%", "100%"); var circle2 = paper2.circle(40, 40, 30); circle2.attr("fill", "red"); circle2.id = "circle"; //both circles get the same id circle2.drag(drag2, start2, up2); </script> </body>

    Read the article

  • Javascript redeclared global variable overrides old value

    - by Yousuf Haider
    I ran into an interesting issue the other day and was wondering if someone could shed light on why this is happening. Here is what I am doing (for the purposes of this example I have dumbed down the example somewhat): I am creating a globally scoped variable using the square bracket notation and assigning it a value. Later I declare a var with the same name as the one I just created above. Note I am not assigning a value. Since this is a redeclaration of the same variable the old value should not be overriden as described here: http://www.w3schools.com/js/js_variables.asp //create global variable with square bracket notation window['y'] = 'old'; //redeclaration of the same variable var y; if (!y) y = 'new'; alert(y); //shows New instead of Old The problem is that the old value actually does get overriden and in the above eg. the alert shows 'new' instead of 'old'. Why ? I guess another way to state my question is how is the above code different in terms of semantics from the code below: //create global variable var y = 'old'; //redeclaration of the same variable var y; if (!y) y = 'new'; alert(y); //shows Old

    Read the article

  • Scope of "library" methods

    - by JS
    Hello, I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help. Background: I'm using the 'if name in "main"' construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their results for visual checking as I develop the modules. To keep things "purdy" and manageable, I've created a small method to simplify the testing of method calls: def pprint_vars(var_in): print("%s = '%s'" % (var_in, eval(var_in))) Calling pprint_vars with: pprint_vars('some_variable_name') prints: some_variable_name = 'foo' All fine and good. Problem statement: Not happy to just KISS, I had the brain-drizzle to move my handy-dandy 'pprint_vars' method into a separate file named 'debug_tools.py' and simply import 'debug_tools' whenever I wanted access to 'pprint_vars'. Here's where things fall apart. I would expect import debug_tools foo = bar debug_tools.pprint_vars('foo') to continue working its magic and print: foo = 'bar' Instead, it greets me with: NameError: name 'some_var' is not defined Irrational belief: I believed (apparently mistakenly) that import puts imported methods (more or less) "inline" with the code, and thus the variable scoping rules would remain similar to if the method were defined inline. Plea for help: Can someone please correct my (mis)understanding of scoping regards imports? Thanks, JS

    Read the article

  • Help needed with Javascript Variable Scope / OOP and Call Back Functions

    - by gargantaun
    I think this issue goes beyond typical variable scope and closure stuff, or maybe I'm an idiot. Here goes anyway... I'm creating a bunch of objects on the fly in a jQuery plugin. The object look something like this function WedgePath(canvas){ this.targetCanvas = canvas; this.label; this.logLabel = function(){ console.log(this.label) } } the jQuery plugin looks something like this (function($) { $.fn.myPlugin = function() { return $(this).each(function() { // Create Wedge Objects for(var i = 1; i <= 30; i++){ var newWedge = new WedgePath(canvas); newWedge.label = "my_wedge_"+i; globalFunction(i, newWedge]); } }); } })(jQuery); So... the plugin creates a bunch of wedgeObjects, then calls 'globalFunction' for each one, passing in the latest WedgePath instance. Global function looks like this. function globalFunction(indicator_id, pWedge){ var targetWedge = pWedge; targetWedge.logLabel(); } What happens next is that the console logs each wedges label correctly. However, I need a bit more complexity inside globalFunction. So it actually looks like this... function globalFunction(indicator_id, pWedge){ var targetWedge = pWedge; someSql = "SELECT * FROM myTable WHERE id = ?"; dbInterface.executeSql(someSql, [indicator_id], function(transaction, result){ targetWedge.logLabel(); }) } There's a lot going on here so i'll explain. I'm using client side database storage (WebSQL i call it). 'dbInterface' an instance of a simple javascript object I created which handles the basics of interacting with a client side database [shown at the end of this question]. the executeSql method takes up to 4 arguments The SQL String an optional arguments array an optional onSuccess handler an optional onError handler (not used in this example) What I need to happen is: When the WebSQL query has completed, it takes some of that data and manipulates some attribute of a particular wedge. But, when I call 'logLabel' on an instance of WedgePath inside the onSuccess handler, I get the label of the very last instance of WedgePath that was created way back in the plugin code. Now I suspect that the problem lies in the var newWedge = new WedgePath(canvas); line. So I tried pushing each newWedge into an array, which I thought would prevent that line from replacing or overwriting the WedgePath instance at every iteration... wedgeArray = []; // Inside the plugin... for(var i = 1; i <= 30; i++){ var newWedge = new WedgePath(canvas); newWedge.label = "my_wedge_"+i; wedgeArray.push(newWedge); } for(var i = 0; i < wedgeArray.length; i++){ wedgeArray[i].logLabel() } But again, I get the last instance of WedgePath to be created. This is driving me nuts. I apologise for the length of the question but I wanted to be as clear as possible. END ============================================================== Also, here's the code for dbInterface object should it be relevant. function DatabaseInterface(db){ var DB = db; this.sql = function(sql, arr, pSuccessHandler, pErrorHandler){ successHandler = (pSuccessHandler) ? pSuccessHandler : this.defaultSuccessHandler; errorHandler = (pErrorHandler) ? pErrorHandler : this.defaultErrorHandler; DB.transaction(function(tx){ if(!arr || arr.length == 0){ tx.executeSql(sql, [], successHandler, errorHandler); }else{ tx.executeSql(sql,arr, successHandler, errorHandler) } }); } // ---------------------------------------------------------------- // A Default Error Handler // ---------------------------------------------------------------- this.defaultErrorHandler = function(transaction, error){ // error.message is a human-readable string. // error.code is a numeric error code console.log('WebSQL Error: '+error.message+' (Code '+error.code+')'); // Handle errors here var we_think_this_error_is_fatal = true; if (we_think_this_error_is_fatal) return true; return false; } // ---------------------------------------------------------------- // A Default Success Handler // This doesn't do anything except log a success message // ---------------------------------------------------------------- this.defaultSuccessHandler = function(transaction, results) { console.log("WebSQL Success. Default success handler. No action taken."); } }

    Read the article

  • In Javascript, a function starts a new scope, but we have to be careful that the function must be in

    - by Jian Lin
    In Javascript, I am sometimes too immerged in the idea that a function creates a new scope, that sometimes I even think the following anonymous function will create a new scope when it is being defined and assigned to onclick: <a href="#" id="link1">ha link 1</a> <a href="#" id="link2">ha link 2</a> <a href="#" id="link3">ha link 3</a> <a href="#" id="link4">ha link 4</a> <a href="#" id="link5">ha link 5</a> <script type="text/javascript"> for (i = 1; i <= 5; i++) { document.getElementById('link' + i).onclick = function() { var x = i; alert(x); return false; } } </script> but in fact, the anonymous function will create a new scope, that's right, but ONLY when it is being invoked, is that so? So the x inside the anonymous function is not created, no new scope is created. When the function was later invoked, there is a new scope alright, but the i is in the outside scope, and the x gets its value, and it is all 6 anyways. The following code will actually invoke a function and create a new scope and that's why the x is a new local variable x in the brand new scope each time, and the invocation of the function when the link is clicked on will use the different x in the different scopes. <a href="#" id="link1">ha link 1</a> <a href="#" id="link2">ha link 2</a> <a href="#" id="link3">ha link 3</a> <a href="#" id="link4">ha link 4</a> <a href="#" id="link5">ha link 5</a> <script type="text/javascript"> for (var i = 1; i <= 5; i++) { (function() { var x = i; document.getElementById('link' + i).onclick = function() { alert(x); return false; } })(); // invoking it now! } </script> If we take away the var in front of x, then it is a global x and so no local variable x is created in the new scope, and therefore, clicking on the links get all the same number, which is the value of the global x.

    Read the article

  • Inherit one instance variable from the global scope

    - by Julian
    I'm using Curses to create a command line GUI with Ruby. Everything's going well, but I have hit a slight snag. I don't think Curses knowledge (esoteric to be fair) is required to answer this question, just Ruby concepts such as objects and inheritance. I'm going to explain my problem now, but if I'm banging on, just look at the example below. Basically, every Window instance needs to have .close called on it in order to close it. Some Window instances have other Windows associated with it. When closing a Window instance, I want to be able to close all of the other Window instances associated with it at the same time. Because associated Windows are generated in a logical fashion, (I append the name with a number: instance_variable_set(self + integer, Window.new(10,10,10,10)) ), it's easy to target generated windows, because methods can anticipate what assosiated windows will be called, (I can recreate the instance variable name from scratch, and almost query it: instance_variable_get(self + integer). I have a delete method that handles this. If the delete method is just a normal, global method (called like this: delete_window(@win543) then everything works perfectly. However, if the delete method is an instance method, which it needs to be in-order to use the self keyword, it doesn't work for a very clear reason; it can 'query' the correct instance variable perfectly well (instance_variable_get(self + integer)), however, because it's an instance method, the global instances aren't scoped to it! Now, one way around this would obviously be to simply make a global method like this: delete_window(@win543). But I have attributes associated with my window instances, and it all works very elegantly. This is very simplified, but it literally translates the problem exactly: class Dog def speak woof end end def woof if @dog_generic == nil puts "@dog_generic isn't scoped when .woof is called from a class method!\n" else puts "@dog_generic is scoped when .woof is called from the global scope. See:\n" + @dog_generic end end @dog_generic = "Woof!" lassie = Dog.new lassie.speak #=> @dog_generic isn't scoped when .woof is called from an instance method!\n woof #=> @dog_generic is scoped when .woof is called from the global scope. See:\nWoof! TL/DR: I need lassie.speak to return this string: "@dog_generic is scoped when .woof is called from the global scope. See:\nWoof!" @dog_generic must remain as an insance variable. The use of Globals or Constants is not acceptable. Could woof inherit from the Global scope? Maybe some sort of keyword: def woof < global # This 'code' is just to conceptualise what I want to do, don't take offence! end Is there some way the .woof method could 'pull in' @dog_generic from the global scope? Will @dog_generic have to be passed in as a parameter?

    Read the article

  • Red Dot Scope Makes Sighting In Long Lenses a Snap

    - by Jason Fitzpatrick
    If you’ve ever used a high power lens, you know how tricky it can be to sight a distant subject as the field of view through the lens is so tiny. This hack takes care of that problem by using a zero-magnification red dot rifle scope. Chris Malcolm enjoys photographing birds and other wildlife with high power lenses. The problem, when shooting with huge 500mm lens and other high power lenses, is that they’re practically telescopes and acquiring a fast moving target like a bird using a through-the-lens technique is very tricky. Malcolm’s solution hinges on mounting a zero-magnification red dot rifle scope in parallel with the lens. His mock up is a bit unpolished (although we can understand not wanting to run out and buy a brand new black scope just for the experiment) but works great to get him on target. Hit up the link below to read more about his build, how be created the rail mount for the scope, and why he opted to mount it to the barrel of the lens and not the hot shoe mount on the camera. 500mm Reflex Lens with Red Dot Sight [via DIY Photography] Make Your Own Windows 8 Start Button with Zero Memory Usage Reader Request: How To Repair Blurry Photos HTG Explains: What Can You Find in an Email Header?

    Read the article

  • How do you create a non-Thread-based Guice custom Scope?

    - by Russ
    It seems that all Guice's out-of-the-box Scope implementations are inherently Thread-based (or ignore Threads entirely): Scopes.SINGLETON and Scopes.NO_SCOPE ignore Threads and are the edge cases: global scope and no scope. ServletScopes.REQUEST and ServletScopes.SESSION ultimately depend on retrieving scoped objects from a ThreadLocal<Context>. The retrieved Context holds a reference to the HttpServletRequest that holds a reference to the scoped objects stored as named attributes (where name is derived from com.google.inject.Key). Class SimpleScope from the custom scope Guice wiki also provides a per-Thread implementation using a ThreadLocal<Map<Key<?>, Object>> member variable. With that preamble, my question is this: how does one go about creating a non-Thread-based Scope? It seems that something that I can use to look up a Map<Key<?>, Object> is missing, as the only things passed in to Scope.scope() are a Key<T> and a Provider<T>. Thanks in advance for your time.

    Read the article

  • Google's 'go' and scope/functions

    - by danwoods
    In one of the example servers given at golang.org: package main import ( "flag" "http" "io" "log" "template" ) var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18 var fmap = template.FormatterMap{ "html": template.HTMLFormatter, "url+html": UrlHtmlFormatter, } var templ = template.MustParse(templateStr, fmap) func main() { flag.Parse() http.Handle("/", http.HandlerFunc(QR)) err := http.ListenAndServe(*addr, nil) if err != nil { log.Exit("ListenAndServe:", err) } } func QR(c *http.Conn, req *http.Request) { templ.Execute(req.FormValue("s"), c) } func UrlHtmlFormatter(w io.Writer, v interface{}, fmt string) { template.HTMLEscape(w, []byte(http.URLEscape(v.(string)))) } const templateStr = ` <html> <head> <title>QR Link Generator</title> </head> <body> {.section @} <img src="http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF- 8&chl={@|url+html}" /> <br> {@|html} <br> <br> {.end} <form action="/" name=f method="GET"><input maxLength=1024 size=70 name=s value="" title="Text to QR Encode"><input type=submit value="Show QR" name=qr> </form> </body> </html> ` Why is template.HTMLEscape(w, []byte(http.URLEscape(v.(string)))) contained within UrlHtmlFormatter? Why can't it be directly linked to "url+html"?

    Read the article

  • ruby on rails named scope implementation

    - by Engwan
    From the book Agile Web Development With Rails class Order < ActiveRecord::Base named_scope :last_n_days, lambda { |days| {:conditions => ['updated < ?' , days] } } named_scope :checks, :conditions => {:pay_type => :check} end The statement orders = Orders.checks.last_n_days(7) will result to only one query to the database. How does rails implement this? I'm new to Ruby and I'm wondering if there's a special construct that allows this to happen. To be able to chain methods like that, the functions generated by named_scope must be returning themselves or an object than can be scoped further. But how does Ruby know that it is the last function call and that it should query the database now? I ask this because the statement above actually queries the database and not just returns an SQL statement that results from chaining.

    Read the article

  • Scope quandary with namespaces, function templates, and static data

    - by Adrian McCarthy
    This scoping problem seems like the type of C++ quandary that Scott Meyers would have addressed in one of his Effective C++ books. I have a function, Analyze, that does some analysis on a range of data. The function is called from a few places with different types of iterators, so I have made it a template (and thus implemented it in a header file). The function depends on a static table of data, AnalysisTable, that I don't want to expose to the rest of the code. My first approach was to make the table a static const inside Analysis. namespace MyNamespace { template <typename InputIterator> int Analyze(InputIterator begin, InputIterator end) { static const int AnalysisTable[] = { /* data */ }; ... // implementation uses AnalysisTable return result; } } // namespace MyNamespace It appears that the compiler creates a copy of AnalysisTable for each instantiation of Analyze, which is wasteful of space (and, to a small degree, time). So I moved the table outside the function like this: namespace MyNamespace { const int AnalysisTable[] = { /* data */ }; template <typename InputIterator> int Analyze(InputIterator begin, InputIterator end) { ... // implementation uses AnalysisTable return result; } } // namespace MyNamespace There's only one copy of the table now, but it's exposed to the rest of the code. I'd rather keep this implementation detail hidden, so I introduced an unnamed namespace: namespace MyNamespace { namespace { // unnamed to hide AnalysisTable const int AnalysisTable[] = { /* data */ }; } // unnamed namespace template <typename InputIterator> int Analyze(InputIterator begin, InputIterator end) { ... // implementation uses AnalysisTable return result; } } // namespace MyNamespace But now I again have multiple copies of the table, because each compilation unit that includes this header file gets its own. If Analyze weren't a template, I could move all the implementation detail out of the header file. But it is a template, so I seem stuck. My next attempt was to put the table in the implementation file and to make an extern declaration within Analyze. // foo.h ------ namespace MyNamespace { template <typename InputIterator> int Analyze(InputIterator begin, InputIterator end) { extern const int AnalysisTable[]; ... // implementation uses AnalysisTable return result; } } // namespace MyNamespace // foo.cpp ------ #include "foo.h" namespace MyNamespace { const int AnalysisTable[] = { /* data */ }; } This looks like it should work, and--indeed--the compiler is satisfied. The linker, however, complains, "unresolved external symbol AnalysisTable." Drat! (Can someone explain what I'm missing here?) The only thing I could think of was to give the inner namespace a name, declare the table in the header, and provide the actual data in an implementation file: // foo.h ----- namespace MyNamespace { namespace PrivateStuff { extern const int AnalysisTable[]; } // unnamed namespace template <typename InputIterator> int Analyze(InputIterator begin, InputIterator end) { ... // implementation uses PrivateStuff::AnalysisTable return result; } } // namespace MyNamespace // foo.cpp ----- #include "foo.h" namespace MyNamespace { namespace PrivateStuff { const int AnalysisTable[] = { /* data */ }; } } Once again, I have exactly one instance of AnalysisTable (yay!), but other parts of the program can access it (boo!). The inner namespace makes it a little clearer that they shouldn't, but it's still possible. Is it possible to have one instance of the table and to move the table beyond the reach of everything but Analyze?

    Read the article

  • Variable Scope Problem, iPhone

    - by Stumf
    Hello all, I need some help here so I will do my best to explain. I have worked on this all day and had no success (just learning!) I have: NSArray *getValue(NSString *iosearch) { ................................. ................................... \\ More code here } - (NSString *) serialnumber { NSArray *results = getValue(@"serial-number"); if (results) return [results objectAtIndex:0]; return nil; } - (NSString *) backlightlevel { NSArray *results = getValue(@"backlight-level"); if (results) return [results objectAtIndex:0]; return nil; } I have a tableView set up and want to display my array in it so I then have: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {............. ......................................................... cell.text = [results objectAtIndex:indexPath.row]; // error results undeclared here return cell; } The problem is I get results undeclared as indicated above. I also can't figure how I could get serialnumber and backlightlevel to display on the click of a button or even at load. My attempts have thrown back errors like error: 'serialnumber' undeclared (first use in this function) and warnings like warning: 'return' with a value, in function returning void. Sorry for the long question! Many thanks, Stuart

    Read the article

  • Sinatra Variable Scope

    - by Ethan Turkeltaub
    Take the following code: ### Dependencies require 'rubygems' require 'sinatra' require 'datamapper' ### Configuration config = YAML::load(File.read('config.yml')) name = config['config']['name'] description = config['config']['description'] username = config['config']['username'] password = config['config']['password'] theme = config['config']['theme'] set :public, 'views/themes/#{theme}/static' ### Models DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/marvin.db") class Post include DataMapper::Resource property :id, Serial property :name, String property :body, Text property :created_at, DateTime property :slug, String end class Page include DataMapper::Resource property :id, Serial property :name, String property :body, Text property :slug, String end DataMapper.auto_migrate! ### Controllers get '/' do @posts = Post.get(:order => [ :id_desc ]) haml :"themes/#{theme}/index" end get '/:year/:month/:day/:slug' do year = params[:year] month = params[:month] day = params[:day] slug = params[:slug] haml :"themes/#{theme}/post.haml" end get '/:slug' do haml :"themes/#{theme}/page.haml" end get '/admin' do haml :"admin/index.haml" end I want to make name, and all those variables available to the entire script, as well as the views. I tried making them global variables, but no dice.

    Read the article

  • How do i fix this JS scope in GM_xmlhttpRequest

    - by acidzombie24
    When i run this code alert 2 shows 6 different href links. alert 3 shows the last href 6 times. How do i make it use the same object (linkdom aka thelink) as alert 2. NOTE: This is in a greasemonkey script { var linkdom = thelink; alert('2' + linkdom.getAttribute("href")); GM_xmlhttpRequest({ method: 'GET', url: href, onload: function(resp){ //... alert('3' + linkdom.getAttribute("href")); } }); //... }

    Read the article

  • Scope of object properties & methods

    - by Anish
    In the article Show love to the object literal, it's said: When we have several scripts in a page, the global variables & functions will get overwritten if their name repeats. One solution is to make the variables as properties & functions as methods of an object, and access them via the object name. But will this prevent the issue of variables getting into the global namespace? <script> var movie = { name: "a", trailer: function(){ //code } }; </script> In the above code which elements gets added to the global namespace? a) Just the object name - movie b) Object name as well as the properties and methods inside it – movie, movie.name, movie.trailer()

    Read the article

  • jquery scope issue

    - by matthewb
    I am having issue with the following: I can't seem to keep the link I am selecting in each repeated item. The word "this" is getting lost. the Var event_id works for each element, but the var $something is undefined? Why is that, Ideally I wanted to do a switch statement but same issue, can't seem to get it to know what link I click and the elements around it to do the action. Updated Full Function: function rsvp (selector,function_url) { $(selector).livequery('click',function(){ var $select = $(selector).attr('rel'); var $event_id= $(this).parents('ul.event-options').attr('rel'); if ($select == "attending") { $(this).closest('span.rsvp-status').html("I'm Attending &ndash; <a href='javascript:;' class='remove' rel='remove'>Remove</a>"); var $something = $(this).parents('ul.event-options').attr('rel'); alert($something); } if ($select == "remove") { $(this).closest('span.rsvp-status').html("Not Attending &ndash; <a href='javascript:;' class='rsvp' rel='attending'>RSVP?</a>"); } if ($select == "interested") { $(this).closest('li').addClass('interested'); $(this).closest('li').removeClass('not-interested'); $(this).closest('li').html("You're Interested"); } $.ajax({ type: "POST", url: "/events/set_member/"+function_url, data: "event_id="+$event_id, beforeSend: function() { $("<span class='notice'>Updating...</span>").prependTo('body'); }, complete: function() { $('span.notice').fadeOut(500); } }); }); } rsvp ('a.rsvp','rsvp'); rsvp ('a.interests','interested'); rsvp ('a.remove','remove'); HTML <ul class="event-options" rel="<?=$event['event_id']?>"> <?php if($event['rsvp_total'] > 0) { ?> <!-- Show Only When Count is Greater than 0 --> <li class="group"><span class="total"><?= $event['rsvp_total']?></span>Interested </li> <?php } ?> <li class="rsvp"><span class="rsvp-status"> Not Attending &ndash; <a href="javascript:;" class="rsvp" rel="attending">RSVP?</a></span></li> <li class="not-interested"> <a href="javascript:;" class="interests" rel="interested"> Interested? </a> </li> <li class="place"><span><a href="<?=$place_path.$event['place_id']?>"><?=$event['place_name']?></a></span></li> <li class="share" rel="<?=$event['event_name']?>"> <a class="sharethis"></a> </li> </ul>

    Read the article

  • Redeclared javascript global variable overrides old value in IE

    - by Yousuf Haider
    (creating a separate question after comments on this: http://stackoverflow.com/questions/2634410/javascript-redeclared-global-variable-overrides-old-value) I am creating a globally scoped variable using the square bracket notation and assigning it a value inside an external js file. In another js file I declare a var with the same name as the one I just created above. Note I am not assigning a value. Since this is a redeclaration of the same variable the old value should not be overriden as described here: http://www.w3schools.com/js/js_variables.asp Create 2 javascript files with the following content : Script1 //create global variable with square bracket notation window['y'] = 'old'; Script2 //redeclaration of the same variable var y; if (!y) y = 'new'; alert(y); //shows New instead of Old in IE Include these 2 files in your html file <html> <head></head> <body> <script type="text/javascript" src="my.js"></script> <script type="text/javascript" src="my2.js"></script> </body> </html> Opening this page in Firefox and Chrome alerts 'old' which is the expected behavior. However in IE 8 the page will actually alert 'new' Any ideas on why this happens on IE ?

    Read the article

  • Safest way to change variable names in a project

    - by kamziro
    So I've been working on a relatively large project by myself, and I've come to realise that some of the variable names earlier on were.. less than ideal. But how does one change variable names in a project easily? Is there such a tool that can go through a project directory, parse all the files, and then replace the variable names to the desired one? It has to be smart enough to understand the language I imagine. I was thinking of using regexp (sed/awk on linux?) tools to just replace the variable name, but there were many times where my particular variable is also included as a part of strings. There's also the issue about changing stuff on a c++ namespace, because there is actually two classes in my project that share the same name, but are in different namespaces. I remember visual stuio being able to do this, but what's the safest and most elegant way to do this on linux?

    Read the article

  • Rails Named Scope and overlapping conditions

    - by Tumtu
    Hi everyone, have a question about rails SQL generation: class Organization < ActiveRecord::Base has_many :people named_scope :active, :conditions => { :active => 'Yes' } end class Person < ActiveRecord::Base belongs_to :organization end Rails SQL for all active people in the first organiztion Organization.first.people.active.all [4;36;1mOrganization Load (0.0ms)[0m [0;1mSELECT TOP 1 * FROM [organizations] [0m [4;35;1mPerson Load (0.0ms)[0m [0mSELECT * FROM [people] WHERE ((([people].[active] = 'Yes') AND ([people].organization_id = 1)) AND ([people].organization_id = 1)) [0m Why Rails generates "[people].organization_id = 1" condition twice ? Does someone know how to make it DRY ? e.g. SELECT * FROM [people] WHERE (([people].[active] = 'Yes') AND ([people].organization_id = 1))

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >