Search Results

Search found 218 results on 9 pages for 'closures'.

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

  • Java 7 closure syntax

    - by xdevel2000
    I download the last Java build b96- Feature Complete for testing the new JDK features but I can't figure out which syntax using for testing closures! Can I test it? Which syntax has been approved in the final release?

    Read the article

  • How to break closures in JavaScript

    - by Not a Name
    Is there any way to break a closure easily in JavaScript? The closest I have gotten is this: var src = 3; function foo () { return function () { return src; } } function bar (func) { var src = 9; return eval('('+func.toString()+')')(); // Line breaks closure } alert(bar(foo())); Which prints 9, instead of 3 as a closure would dictate. However, this approach seems kind of ugly to me, are there any better ways?

    Read the article

  • JS: using 'var me = this' to reference an object instead of using a global array

    - by Marco Demaio
    The example below, is just an example, I know that I don't need an object to show an alert box when user clicks on div blocks, but it's just a simple example to explain a situation that frequently happens when writing JS code. In the example below I use a globally visible array of objects to keep a reference to each new created HelloObject, in this way events called when clicking on a div block can use the reference in the arry to call the HelloObject's public function hello(). 1st have a look at the code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Test </title> <script type="text/javascript"> /***************************************************** Just a cross browser append event function, don't need to understand this one to answer my question *****************************************************/ function AppendEvent(html_element, event_name, event_function) {if(html_element) {if(html_element.attachEvent) html_element.attachEvent("on" + event_name, event_function); else if(html_element.addEventListener) html_element.addEventListener(event_name, event_function, false); }} /****************************************************** Just a test object ******************************************************/ var helloobjs = []; var HelloObject = function HelloObject(div_container) { //Adding this object in helloobjs array var id = helloobjs.length; helloobjs[id] = this; //Appending click event to show the hello window AppendEvent(div_container, 'click', function() { helloobjs[id].hello(); //THIS WORKS! }); /***************************************************/ this.hello = function() { alert('hello'); } } </script> </head><body> <div id="one">click me</div> <div id="two">click me</div> <script type="text/javascript"> var t = new HelloObject(document.getElementById('one')); var t = new HelloObject(document.getElementById('two')); </script> </body></html> In order to achive the same result I could simply replace the code //Appending click event to show the hello window AppendEvent(div_container, 'click', function() { helloobjs[id].hello(); //THIS WORKS! }); with this code: //Appending click event to show the hello window var me = this; AppendEvent(div_container, 'click', function() { me.hello(); //THIS WORKS TOO AND THE GLOBAL helloobjs ARRAY BECOMES SUPEFLOUS! }); thus would make the helloobjs array superflous. My question is: does this 2nd option in your opinion create memoy leaks on IE or strange cicular references that might lead to browsers going slow or to break??? I don't know how to explain, but coming from a background as a C/C++ coder, doing in this 2nd way sounds like a some sort of circular reference that might break memory at some point. I also read on internet about the IE closures memory leak issue http://jibbering.com/faq/faq_notes/closures.html (I don't know if it was fixed in IE7 and if yes, I hope it does not come out again in IE8). Thanks

    Read the article

  • What is the need of functional programming?

    - by Lazer
    I have read about functional programming which is stateless, gives the same result invocation after invocation, about closures and other related concepts. I still feel that I have very little idea what these things are about. Thinking about this, right now, I feel complete in C, C++, and Java. Any programming problem and I start thinking in one of these languages. So, I never feel and understand the need for functional languages. A good starting point therefore would be to try to understand some things that are not possible in imperative languages but possible in functional languages. I feel unless I understand where exactly functional languages fit inside my already complete world of C, C++ and Java, I would never be able to appreciate and understand them. So, can somebody help me understand the real need for functional programming? Where exactly do they fit in?

    Read the article

  • C# -Closure -Clarification

    - by nettguy
    I am learning C#.Can I mean closure as a construct that can adopt the changes in the environment in which it is defined. Example : List<Person> gurus = new List<Person>() { new Person{id=1,Name="Jon Skeet"}, new Person{id=2,Name="Marc Gravell"}, new Person{id=3,Name="Lasse"} }; void FindPersonByID(int id) { gurus.FindAll(delegate(Person x) { return x.id == id; }); } The variable id is declared in the scope of FindPersonByID() but t we still can access the local variable id inside the anonymous function (i.e) delegate(Person x) { return x.id == id; } (1) Is my understanding of closure is correct ? (2) What are the aditional advantages can we get from closures?

    Read the article

  • Javascript: variable in outer function not changed by inner function

    - by Weng-Lock Mok
    I am having a small issue with what I believe is probably my misunderstanding of Javascript closures. I have this piece of code -- getStdOpts: function(tbl, filt) { var vals = new Array(); this.srvs.getStdOptions( { tbl: tbl }, { 'ok': function(rsp) { for (var i in rsp) { vals.push({ value: rsp[i].id, text: rsp[i].descr }); } } } ); return vals; } In essence, although the inner function inside the getStdOptions call ('ok': function...) pushes new values into the vals array, when accessed from outside the call, the vals array is empty. When accessed from within the inner function, vals contains all the elements as expected. Would really appreciate any help I can get on this matter.

    Read the article

  • What is a practical use for a closure in JavaScript?

    - by alex
    I'm trying my hardest to wrap my head around JavaScript's closures. I get that by returning an inner function, it will have access to any variable defined in it's immediate parent. Where would this be useful to me? Perhaps I haven't quite got my head around it yet. Most of the examples I have seen online don't provide any real world code, just vague examples. Can someone show me a real world use of a closure? Is this one, for example? var warnUser = function (msg) { var calledCount = 0; return function() { calledCount++; alert(msg + '\nYou have been warned ' + calledCount + ' times.'); }; }; var warnForTamper = warnUser('You can not tamper with our HTML.'); warnForTamper(); warnForTamper(); Thanks

    Read the article

  • What is the correct way to fix this Javascript closure

    - by sujoe
    I have been familiarizing myself with javascript closures and ran across this article http://blog.morrisjohns.com/javascript_closures_for_dummies.html Due to the closure, Example 5 does not work as expected. How would one modify result.push( function() {alert(item + ' ' + list[i])} ); to make the code work? function buildList(list) { var result = []; for (var i = 0; i < list.length; i++) { var item = 'item' + list[i]; result.push( function() {alert(item + ' ' + list[i])} ); } return result; } function testList() { var fnlist = buildList([1,2,3]); // using j only to help prevent confusion - could use i for (var j = 0; j < fnlist.length; j++) { fnlist[j](); } } testList(); Thanks!

    Read the article

  • How can I create a new Person object correctly in Javascript?

    - by TimDog
    I'm still struggling with this concept. I have two different Person objects, very simply: ;Person1 = (function() { function P (fname, lname) { P.FirstName = fname; P.LastName = lname; return P; } P.FirstName = ''; P.LastName = ''; var prName = 'private'; P.showPrivate = function() { alert(prName); }; return P; })(); ;Person2 = (function() { var prName = 'private'; this.FirstName = ''; this.LastName = ''; this.showPrivate = function() { alert(prName); }; return function(fname, lname) { this.FirstName = fname; this.LastName = lname; } })(); And let's say I invoke them like this: var s = new Array(); //Person1 s.push(new Person1("sal", "smith")); s.push(new Person1("bill", "wonk")); alert(s[0].FirstName); alert(s[1].FirstName); s[1].showPrivate(); //Person2 s.push(new Person2("sal", "smith")); s.push(new Person2("bill", "wonk")); alert(s[2].FirstName); alert(s[3].FirstName); s[3].showPrivate(); The Person1 set alerts "bill" twice, then alerts "private" once -- so it recognizes the showPrivate function, but the local FirstName variable gets overwritten. The second Person2 set alerts "sal", then "bill", but it fails when the showPrivate function is called. The new keyword here works as I'd expect, but showPrivate (which I thought was a publicly exposed function within the closure) is apparently not public. I want to get my object to have distinct copies of all local variables and also expose public methods -- I've been studying closures quite a bit, but I'm still confused on this one. Thanks for your help.

    Read the article

  • Use queried json data in a function

    - by SztupY
    I have a code similar to this: $.ajax({ success: function(data) { text = ''; for (var i = 0; i< data.length; i++) { text = text + '<a href="#" id="Data_'+ i +'">' + data[i].Name + "</a><br />"; } $("#SomeId").html(text); for (var i = 0; i< data.length; i++) { $("#Data_"+i).click(function() { alert(data[i]); RunFunction(data[i]); return false; }); } } }); This gets an array of some data in json format, then iterates through this array generating a link for each entry. Now I want to add a function for each link that will run a function that does something with this data. The problem is that the data seems to be unavailable after the ajax success function is called (although I thought that they behave like closures). What is the best way to use the queried json data later on? (I think setting it as a global variable would do the job, but I want to avoid that, mainly because this ajax request might be called multiple times) Thanks.

    Read the article

  • How to copy a variable in JavaScript?

    - by Michael Stum
    I have this JavaScript code: for (var idx in data) { var row = $("<tr></tr>"); row.click(function() { alert(idx); }); table.append(row); } So I'm looking through an array, dynamically creating rows (the part where I create the cells is omitted as it's not important). Important is that I create a new function which encloses the idx variable. However, idx is only a reference, so at the end of the loop, all rows have the same function and all alert the same value. One way I solve this at the moment is by doing this: function GetRowClickFunction(idx){ return function() { alert(idx); } } and in the calling code I call row.click(GetRowClickFunction(idx)); This works, but is somewhat ugly. I wonder if there is a better way to just copy the current value of idx inside the loop? While the problem itself is not jQuery specific (it's related to JavaScript closures/scope), I use jQuery and hence a jQuery-only solution is okay if it works.

    Read the article

  • How to preserve the state of JavaScript closure?

    - by Uccio
    I am working on a migration platform to migrate web applications from a device to another. I am extending it to add the support for preserving JavaScript state. My main task is to create a file representing the current state of the executing application, to transmit it to another device and to reload the state in the destination device. The basic solution I adopted is to navigate the window object and to save all its descendant properties using JSON as base format for exportation and extending it to implement some features: preserving object reference, even if cyclic (dojox.json.ref library) support for timers Date non-numericproperties of arrays reference to DOM elements The most important task I need to solve now is exportation of closures. At this moment I didn't know how to implement this feature. I read about the internal EcmaScript property [[scope]] containing the scope chain of a function, a list-like object composed by all the nested activation context of the function. Unfortunately it is not accessible by JavaScript. Anyone know if there is a way to directly access the [[scope]] property? Or another way to preserve the state of a closure?

    Read the article

  • How to create custom MouseEvent.CLICK event in AS3 (pass parameters to function)?

    - by fromvega
    Hello, This question doesn't relate only to MouseEvent.CLICK event type but to all event types that already exist in AS3. I read a lot about custom events but until now I couldn't figure it out how to do what I want to do. I'm going to try to explain, I hope you understand: Here is a illustration of my situation: for(var i:Number; i < 10; i++){ var someVar = i; myClips[i].addEventListener(MouseEvent.CLICK, doSomething); } function doSomething(e:MouseEvent){ /* */ } But I want to be able to pass someVar as a parameter to doSomething. So I tried this: for(var i:Number; i < 10; i++){ var someVar = i; myClips[i].addEventListener(MouseEvent.CLICK, function(){ doSomething(someVar); }); } function doSomething(index){ trace(index); } This kind of works but not as I expect. Due to the function closures, when the MouseEvent.CLICK events are actually fired the for loop is already over and someVar is holding the last value, the number 9 in the example. So every click in each movie clip will call doSomething passing 9 as the parameter. And it's not what I want. I thought that creating a custom event should work, but then I couldn't find a way to fire a custom event when the MouseEvent.CLICK event is fired and pass the parameter to it. Now I don't know if it is the right answer. What should I do and how?

    Read the article

  • Queue ExternalInterface calls to Flash Object in UpdatePanel - Needs Improvement?

    - by Laramie
    A Flash (actually Flex) object is created on an ASP.Net page within an Update Panel using a modified version of the embedCallAC_FL_RunContent.js script so it can be written in dynamically. It is re-created with this script with each partial postback to that panel. There are also other Update Panels on the page. With some postbacks (partial and full), External Interface calls such as $get('FlashObj').ExternalInterfaceFunc('arg1', 0, true); are prepared server-side and added to the page using ScriptManager.RegisterStartupScript. They're embedded in a function and stuffed into Sys.Application's load event, for example Sys.Application.add_load(funcContainingExternalInterfaceCalls). The problem is that because the Flash object's state state may change with each partial postback, the Flash (Flex) object and/or External Interface may not be ready or even exist yet in the DOM when the JavaScript - Flash External Interface call is made. It results in an "Object doesn't support this property or method" exception. I have a working strategy to make the ExternalInterface calls immediately if Flash is ready or else queue them until such time that Flash announces its readiness. //Called when the Flash object is initialized and can accept ExternalInterfaceCalls var flashReady = false; //Called by Flash when object is fully initialized function setFlashReady() { flashReady = true; //Make any queued ExternalInterface calls, then dequeue while (extIntQueue.length > 0) (extIntQueue.shift())(); } var extIntQueue = []; function callExternalInterface(flashObjName, funcName, args) { //reference to the wrapped ExternalInterface Call var wrapped = extWrap(flashObjName, funcName, args); //only procede with ExternalInterface call if the global flashReady variable has been set if (flashReady) { wrapped(); } else { //queue the function so when flashReady() is called next, the function is called and the aruments are passed. extIntQueue.push(wrapped); } } //bundle ExtInt call and hold variables in a closure function extWrap(flashObjName, funcName, args) { //put vars in closure return function() { var funcCall = '$get("' + flashObjName + '").' + funcName; eval(funcCall).apply(this, args); } } I set the flashReady var to dirty whenever I update the Update Panel that contains the Flash (Flex) object. ScriptManager.RegisterClientScriptBlock(parentContainer, parentContainer.GetType(), "flashReady", "flashReady = false;", true); I'm pleased that I got it to work, but it feels like a hack. I am still on the learning curve with respect to concepts like closures why "eval()" is apparently evil, so I'm wondering if I'm violating some best practice or if this code should be improved, if so how? Thanks.

    Read the article

  • Oracle redonne un élan au Projet Lambda sur Java 7 et les closures : Interface evolution via "public

    Bonjour, Depuis quelques temps, on n'entendait plus trop parler des Closures et de leur ajout à Java 7. En réponse à David Flanagan qui s'inquiétait récemment du silence d'Oracle et de la stagnation du Project Lambda, Brian Goetz (Oracle) a soumis il y a quelques jours un document de réflexion sur la notion de virtual extension methods permettant d'ajouter sur une interface existante de nouvelles méthodes (avec des implémentations par défaut) sans casser le contrat avec le code existant.

    Read the article

  • Question on Scala Closure (From "Programming in Scala")

    - by Ekkmanz
    I don't understand why authors said that Code Listing 9.1 from "Programming in Scala" use closure. In chapter 9, they show how to refactor code into more less duplicated form, from this original code: object FileMatcher { private def filesHere = (new java.io.File(".")).listFiles def filesEnding(query: String) = for (file <- filesHere; if file.getName.endsWith(query)) yield file def filesContaining(query: String) = for (file <- filesHere; if file.getName.contains(query)) yield file def filesRegex(query: String) = for (file <- filesHere; if file.getName.matches(query)) yield file } To the second version: object FileMatcher { private def filesHere = (new java.io.File(".")).listFiles def filesMatching(query: String, matcher: (String, String) => Boolean) = { for (file <- filesHere; if matcher(file.getName, query)) yield file } def filesEnding(query: String) = filesMatching(query, _.endsWith(_)) def filesContaining(query: String) = filesMatching(query, _.contains(_)) def filesRegex(query: String) = filesMatching(query, _.matches(_)) } Which they said that there is no use of closure here. Now I understand until this point. However they introduced the use of closure to refactor even some more, shown in Listing 9.1: object FileMatcher { private def filesHere = (new java.io.File(".")).listFiles private def filesMatching(matcher: String => Boolean) = for (file <- filesHere; if matcher(file.getName)) yield file def filesEnding(query: String) = filesMatching(_.endsWith(query)) def filesContaining(query: String) = filesMatching(_.contains(query)) def filesRegex(query: String) = filesMatching(_.matches(query)) } Now they said that query is a free variable but I don't really understand why they said so? Since ""query"" seems to be passed from top method down to string matching function explicitly.

    Read the article

  • JScript.NET private variables

    - by Paul Podlipensky
    I'm wondering about JScript.NET private variables. Please take a look on the following code: import System; import System.Windows.Forms; import System.Drawing; var jsPDF = function(){ var state = 0; var beginPage = function(){ state = 2; out('beginPage'); } var out = function(text){ if(state == 2){ var st = 3; } MessageBox.Show(text + ' ' + state); } var addHeader = function(){ out('header'); } return { endDocument: function(){ state = 1; addHeader(); out('endDocument'); }, beginDocument: function(){ beginPage(); } } } var j = new jsPDF(); j.beginDocument(); j.endDocument(); Output: beginPage 2 header 2 endDocument 2 if I run the same script in any browser, the output is: beginPage 2 header 1 endDocument 1 Why it is so?? Thanks, Paul.

    Read the article

  • When to use closure?

    - by shahkalpesh
    I have seen samples of closure from - http://stackoverflow.com/questions/36636/what-is-a-closure Can anyone provide simple example of when to use closure? Specifically, scenarios in which closure makes sense? Lets assume that the language doesn't have closure support, how would one still achieve similar thing? Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc. I am sorry, I do not understand functional languages yet.

    Read the article

  • Access to modified closure, is this a ReSharper bug?

    - by hmemcpy
    I have the latest ReSharper 5.0 build (1655), where I have encountered the suggestion 'Access to modified closure' on the following code: var now = new DateTime(1970, 1, 1); var dates = new List<DateTime>(); dates.Where(d => d > now); and the now inside the lambda expression is underlined with the warning. I'm pretty sure that's a ReSharper bug, but is it really?

    Read the article

  • "return false" is ignored in certain browsers for link added dynamically to the DOM with JavaScript

    - by AlexV
    I dynamically add an <a> (link) tag to the DOM with: var link = document.createElement('a'); link.href = 'http://www.google.com/'; link.onclick = function () { window.open(this.href); return false; }; link.appendChild(document.createTextNode('Google')); //someDomNode.appendChild(link); I want the link to open in a new window (I know it's bad, but it's required) and I don't want to use the target attribute. My code works well in IE and Firefox, but the return false don't work in Safari, Chrome and Opera. By don't work I mean the link is followed after the new window is opened.

    Read the article

  • When actually is a closure created?

    - by Jian Lin
    Is it true that a closure is created in the following cases for foo, but not for bar? Case 1: <script type="text/javascript"> function foo() { } </script> foo is a closure with a scope chain with only the global scope. Case 2: <script type="text/javascript"> var i = 1; function foo() { return i; } </script> same as Case 1. Case 3: <script type="text/javascript"> function Circle(r) { this.r = r; } Circle.prototype.foo = function() { return 3.1415 * this.r * this.r } </script> in this case, Circle.prototype.foo (which returns the circle's area) refers to a closure with only the global scope. (this closure is created). Case 4: <script type="text/javascript"> function foo() { function bar() { } } </script> here, foo is a closure with only the global scope, but bar is not a closure (yet), because the function foo is not invoked in the code, so no closure goo is ever created. It will only exist if foo is invoked , and the closure bar will exist until foo returns, and the closure bar will then be garbage collected, since there is no reference to it at all anywhere. So when the function doesn't exist, can't be invoked, can't be referenced, then the closure doesn't exist yet (never created yet). Only when the function can be invoked or can be referenced, then the closure is actually created?

    Read the article

  • Ugly thing and advantage of anonymos method -C#

    - by nettguy
    I was asked to explain the ugly thing and advantages of anonymous method. I explained possibly Ugly thing anonymous methods turning quickly into spaghetti code. Advantages We can produce thread safe code using anonymous method :Example static List<string> Names = new List<string>( new string[] { "Jon Skeet", "Marc Gravell", "David", "Bill Gates" }); static List<string> FindNamesStartingWith(string startingText) { return Names.FindAll( delegate(string name) { return name.StartsWith(startingText); }); } But really i did not know whether it is thread safe or not.I was asked to justify it. Can any one help me to understand (1) advantages of anonymous methods (2) Is the above code thread safe or not?

    Read the article

  • In languages which create a new scope each time in a loop block, a new local copy of the local loop

    - by Jian Lin
    It seems that in language like C, Java, and Ruby (as opposed to Javascript), a new scope is created for each iteration of a loop block, and the local variable defined for the loop is actually made into a local variable every single time and recorded in this new scope? For example, in Ruby: p RUBY_VERSION $foo = [] (1..5).each do |i| $foo[i] = lambda { p i } end (1..5).each do |j| $foo[j].call() end the print out is: [MacBook01:~] $ ruby scope.rb "1.8.6" 1 2 3 4 5 [MacBook01:~] $ So, it looks like when a new scope is created, a new local copy of i is also created and recorded in this new scope, so that when the function is executed at a later time, the "i" is found in those scope chains as 1, 2, 3, 4, 5 respectively. Is this true? (It sounds like a heavy operation). Contrast that with p RUBY_VERSION $foo = [] i = 0 (1..5).each do |i| $foo[i] = lambda { p i } end (1..5).each do |j| $foo[j].call() end This time, the i is defined before entering the loop, so Ruby 1.8.6 will not put this i in the new scope created for the loop block, and therefore when the i is looked up in the scope chain, it always refer to the i that was in the outside scope, and give 5 every time: [MacBook01:~] $ ruby scope2.rb "1.8.6" 5 5 5 5 5 [MacBook01:~] $ I heard that in Ruby 1.9, i will be treated as a local defined for the loop even when there is an i defined earlier? The operation of creating a new scope, creating a new local copy of i each time through the loop seems heavy, as it seems it wouldn't have matter if we are not invoking the functions at a later time. So when the functions don't need to be invoked at a later time, could the interpreter and the compiler to C / Java try to optimize it so that there is not local copy of i each time?

    Read the article

  • Multiple return points in scala closure/anonymous function

    - by Debilski
    As far as I understand it, there is no way in Scala to have multiple return points in an anonymous function, i.e. someList.map((i) => { if (i%2 == 0) return i // the early return allows me to avoid the else clause doMoreStuffAndReturnSomething(i) }) raises an error: return outside method definition. (And if it weren’t to raise that, the code would not work as I’d like it to work.) One workaround I could thing of would be the following someList.map({ def f(i: Int):Int = { if (i%2 == 0) return i doMoreStuffAndReturnSomething(i) } f }) however, I’d like to know if there is another ‘accepted’ way of doing this. Maybe a possibility to go without a name for the inner function? (A use case would be to emulate some valued continue construct inside the loop.)

    Read the article

  • Inheritance of closure objects and overriding of methods

    - by bobikk
    I need to extend a class, which is encapsulated in a closure. This base class is following: var PageController = (function(){ // private static variable var _current_view; return function(request, new_view) { ... // priveleged public function, which has access to the _current_view this.execute = function() { alert("PageController::execute"); } } })(); Inheritance is realised using the following function: function extend(subClass, superClass){ var F = function(){ }; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; subClass.superclass = superClass.prototype; StartController.cache = ''; if (superClass.prototype.constructor == Object.prototype.constructor) { superClass.prototype.constructor = superClass; } } I subclass the PageController: var StartController = function(request){ // calling the constructor of the super class StartController.superclass.constructor.call(this, request, 'start-view'); } // extending the objects extend(StartController, PageController); // overriding the PageController::execute StartController.prototype.execute = function() { alert('StartController::execute'); } Inheritance is working. I can call every PageController's method from StartController's instance. However, method overriding doesn't work: var startCont = new StartController(); startCont.execute(); alerts "PageController::execute". How should I override this method?

    Read the article

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