Search Results

Search found 4509 results on 181 pages for 'scope chain'.

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

  • 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

  • IFMR Conference – Global Procurement & Supply Chain Management for the Oil & Gas Industry

    - by Pam Petropoulos
    Dates: June 9 - 11, 2014Location: JW Marriott Houston, TXThis 2nd Global Procurement and Supply Chain Management Conference for the Oil & Gas Industry will cover key market challenges including: - supplier / operator relationships- benchmarking strategic procurement and category management- capacity overload vs. demand- new frontiers /new procurement strategies - sustainability in procurement and supply chain With a one-track focus, this is a highly intensive, content-driven event that includes case studies, presentations and panel discussions over two full days.Plan to attend the Oracle presentation on day one, and the Oracle panel discussion on day two. Oil & Gas experts will be available in the Oracle booth to answer questions.Click here to learn more and register.

    Read the article

  • ArvinMeritor Sees Business Improvement: Uses Oracle Demand Management, Supply Chain Planning and Tra

    - by [email protected]
    As manufacturers begin repositioning for the economic recovery, they are reevaluating their supply chain networks, extending lean into their supply chains and making logistics visibility a priority. ArvinMeritor leveraged Oracle's Demantra, ASCP and Transportation Management applications to: Optimize operations execution by building consensus-driven demand, sales and operations plans Slash transportation costs by rationalizing shippers, optimizing routes and improving delivery performance Demantra for demand management, forecasting, sales and operations planning and global trade management Advanced Supply Chain Planning for material and capacity planning across global distribution and manufacturing facilities based on consensus forecasts, sales orders, production status, purchase orders, and inventory policy recommendations Transportation Management for transportation planning, execution, freight payment, and business process automation on a single application across all modes of transportation, from full truckload to complex multileg air, ocean, and rail shipments Oracle hosted an 'open-house/showcase" on March 30th, 2010 atArvinMeritor Global Headquarters 2135 West Maple RoadTroy, MI 48084 

    Read the article

  • Toyota's Supply Chain "ran too hot"

    - by [email protected]
    The Feb 28th '10 edition of the Economist had a very informative artical (pg.74) on Toyota's over-stretched supply chain pointing out that they were ' the author of most of its own misfortunes".  James Womack is quoted in the piece on Toyota's rapid expansion 'meant working with a lot of unfamiliar suppliers who didn't have a deep understandin of Toyota's culture.  The majority of the problems almost certainly originated not in the Toyota factories but in those of the supppliers'. One purchasing executive said that it started in mid-2008, when the weaker parts of the supply chain were put under great strain. There is a need for visibility but not always there. Firms need transparancy and speed of communications to make sure defective parts and errors dont reach the customer. It concludes with guidance to manufacturers: "It may be safer not to have all your eggs in one basket, but to have maybe 3 suppliers for major components who can benchmark each other' - Toyota was the peerless exemplar, now seen as an awful warning

    Read the article

  • Video White Paper: Mega-Project Management: Reducing Risk & Complexity across the Value Chain

    - by Melissa Centurio Lopes
    Watch this short video white paper, to learn how Oracle Primavera can help you keep projects on track and protect your investments. You can also download the full white paper “Mega-Project Management: Reducing Risk & Complexity Across the Value Chain” to gain more in depth information about strategies for collaborating and sharing information and data in a systematic way across the value chain. Download the white paper in order to learn how your company can get the expected payoff from your next mega project. Register now to download the full complementary white paper, and discover how to: Improve decision-making and accountability through enterprise-wide visibility, workflows, and collaboration Reduce financial and performance risk

    Read the article

  • Hear about Oracle Supply Chain at Pella, Apr 27-29 '10

    - by [email protected]
    Oracle Customer Showcase - Apr 27-29'10 Featuring Pella Corp. Delivering Greater Customer Value "Discovering the Lean Value Chain" Pella is once again hosting Oracle customers at a mega-reference event in Pella, Iowa, on April 27-29. The agenda features a cross-stack set of topics and issues, including strategies for delivering customer value, improving the customer experience, Value Chain Planning / Manufacturing / Enterprise Performance Management, and Lean practices. Several executives will keynote, including Pella CIO Steve Printz. The event includes a demo grounds, round-table discussion groups, plant tours, and networking opportunities. !  

    Read the article

  • Grams to Pounds: A Domino Chain Reaction [Video]

    - by Jason Fitzpatrick
    Most of us have seen a domino knock down or two in our day, but this demonstration video shows how a series of increasingly larger dominoes allow a tiny domino to knock over a 100 pound domino. A domino can knock over another domino about 50% larger than itself. A chain of dominos of increasing size makes a kind of mechanical chain reaction that starts with a tiny push and knocks down an impressively large domino. The only question we have after watching the video is: where can we find 29 appropriately sized dominoes? [via Neatorama] HTG Explains: What Is Windows RT and What Does It Mean To Me? HTG Explains: How Windows 8′s Secure Boot Feature Works & What It Means for Linux Hack Your Kindle for Easy Font Customization

    Read the article

  • Product Value Chain Management: How Oracle is Taking the Lead on Next Generation Enterprise PLM

    To manage growing product complexity and innovation challenges, Product Lifecycle Management solutions have become staple IT investments over the years. But as product information continues to span more and more functions inside the company and out, we've seen many customer PLM implementations adapt and expand to serve new needs in a fully connected world. We call this next level of PLM the Product Value Chain, an integrated business model that offers powerful new strategies for executives to collectively leverage PLM other industry leading Oracle applications to achieve further incremental value. In this Appcast, hear Terri Hiskey, Director PLM Product Marketing, and John Kelley, VP PLM Product Strategy, discuss Oracle's vision for next generation enterprise PLM: the Product Value Chain.

    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

  • Designing a chain of states

    - by devoured elysium
    I want to model a kind of FSM(Finite State Machine). I have a sequence of states (let's say, from StateA to StateZ). This sequence is called a Chain and is implemented internally as a List. I will add states by the order I want them to run. My purpose is to be able to make a sequence of actions in my computer (for example, mouse clicks). (I know this has been done a zillion times). So a state is defined as a: boolean Precondition() <- Checks to see if for this state, some condition is true. For example, if I want to click in the Record button of a program, in this method I would check if the program's process is running or not. If it is, go to the next state in the chain list, otherwise, go to what was defined as the fail state (generally is the first state of them all). IState GetNextState() <- Returns the next state to evaluate. If Precondition() was sucessful, it should yield the next state in the chain otherwise it should yield the fail state. Run() Simply checks the Precondition() and sets the internal data so GetNextState() works as expected. So, a naive approach to this would be something like this: Chain chain = new Chain(); //chain.AddState(new State(Precondition, FailState, NextState) <- Method structure chain.AddState(new State(new WinampIsOpenCondition(), null, new <problem here, I want to referr to a state that still wasn't defined!>); The big problem is that I want to make a reference to a State that at this point still wasn't defined. I could circumvent the problem by using strings when refrering to states and using an internal hashtable, but isn't there a clearer alternative? I could just pass only the pre-condition and failure states in the constructor, having the chain just before execution put in each state the correct next state in a public property but that seems kind of awkward.

    Read the article

  • 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

  • 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

  • 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

  • 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

  • anonymous function variable scope [js, ajax]

    - by arthurprs
    $(".delete").click( function() { var thesender = this; $(thesender).text("Del..."); $.getJSON("ajax.php", {}, function(data) { if (data["result"]) $(thesender).remove(); // variable defined outside else alert('Error!'); } ); return false; } ); This can cause problems if user clicks on another ".delete" before the ajax callback is called?

    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

  • javascript scope problem when lambda function refers to a variable in enclosing loop

    - by Stefan Blixt
    First question on stackoverflow :) Hope I won't embarrass myself... I have a javascript function that loads a list of albums and then it creates a list item for each album. The list item should be clickable, so I call jQuery's click() with a function that does stuff. I do this in a loop. My problem is that all items seem to get the same click function, even though I try to make a new one that does different stuff in each iteration. Another possibility is that the iteration variable is global somehow, and the function refers to it. Code below. debug() is just an encapsulation of Firebug's console.debug(). function processAlbumList(data, c) { for (var album in data) { var newAlbum = $('<li class="albumLoader">' + data[album].title + '</li>').clone(); var clickAlbum = function() { debug("contents: " + album); }; debug("Album: " + album + "/" + data[album].title); $('.albumlist').append(newAlbum); $(newAlbum).click(clickAlbum); } } Here is a transcript of what it prints when the above function runs, after that are some debug lines caused by me clicking on different items. It always prints "10", which is the last value that the album variable takes (there are 10 albums). Album: 0/Live on radio.electro-music.com Album: 1/Doodles Album: 2/Misc Stuff Album: 3/Drawer Collection Album: 4/Misc Electronic Stuff Album: 5/Odds & Ends Album: 6/Tumbler Album: 7/Bakelit 32 Album: 8/Film Album: 9/Bakelit Album: 10/Slow Zoom/Atomic Heart contents: 10 contents: 10 contents: 10 contents: 10 contents: 10 Any ideas? Driving me up the wall, this is. :) /Stefan

    Read the article

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