Search Results

Search found 1405 results on 57 pages for 'prototype'.

Page 17/57 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • javascript constructor reset: What is it ?

    - by Sake
    I came across this slide: http://www.slideshare.net/stoyan/javascript-patterns#postComment at page 35: Option 5 + super + constructor reset function inherit(C, P) { var F = function(){}; F.prototype = P.prototype; C.prototype = new F(); C.uber = P.prototype; C.prototype.constructor = C; // WHY ??? } I don't get it. Can anybody please explain what the last line for ? C.prototype.constructor = C; // WHY ??? Thanks

    Read the article

  • Are google chrome extension "content" scripts sandboxed?

    - by jabapyth
    I was under the impression that the content_scripts were executed right on the page, but it now seems as though there's some sandboxing going on. I'm working on an extension to log all XHR traffic of a site (for debugging and other development purposes), and in the console, the following sniff code works: var o = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function(){ console.log(arguments, 'open'); return o.apply(this, arguments); }; console.log('myopen'); console.log(window, window.XMLHttpRequest, window.XMLHttpRequest.prototype, o, window.XMLHttpRequest.prototype.open); This logs a message everytime an XHR is sent. When I put this in an extension, however, the real prototype doesn't get modified. Apparently the window.XMLHttpRequest.prototype that my script is seeing differs from that of the actual page. Is there some way around this? Also, is this sandboxing behavior documented anywhere? I looked around, but couldn't find anything.

    Read the article

  • Prototype.js: How can i return an array without all the methods Prototypes extends Array with?

    - by Morten
    Hi! Is there a way to return a new version of an array/hash that does not contain all the methods/functions that prototype extends the array object with? Example: var myArray = $A(); myArray['test'] = '1'; myArray['test2'] = '2'; var myVariableToPassToAjax = myArray; If I debug myVariableToPassToAjax it looks like this: Array ( [test] = 1 [test2] = 2 [each] = function each(iterator, context) { .......... .......... } ...and all the other extended array functions ); Is there a way to solve this? :-/ Morten

    Read the article

  • How can I use this downloaded Class(es) on my Prototype Routine?

    - by O.C.
    I'm a newbie and I'm in need of some help. I'm working on a prototype for an app, but I'm learning at the same time. I want to display a popup image over a given UIView, but I would like it to behave like the UIAlertView or like the Facebook Connect for iPhone modal popup window, in that it has a bouncy, rubbber-band-like animation to it. I was able to find the following class(es) on the net, from someone who was trying to do something similar. He/she put this together, but there was no Demo, no instructions nor a way to contact them. Being that I am so new, I don't have any idea as to how to incorporate this into my code. This is the routine where I need the bouncy image to appear... //======================================================== // // productDetail // - (void) showProductDetail { _productDetailIndex++; if (_productDetailIndex > 7) { return; } else if (_productDetailIndex == 1) { NSString* filename = [NSString stringWithFormat:@"images/ICS_CatalogApp_0%d_ProductDetailPopup.png", _productDetailIndex]; [_productDetail setImageWithName:filename]; _productDetail.transform = CGAffineTransformMakeScale(0.1,0.1); [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.5]; // other animations goes here _productDetail.transform = CGAffineTransformMakeScale(1,1); // other animations goes here [UIView commitAnimations]; } NSString* filename = [NSString stringWithFormat:@"images/ICS_CatalogApp_0%d_ProductDetailPopup.png", _productDetailIndex]; [_productDetail setImageWithName:filename]; _productDetail.x = (self.width - _productDetail.width); _productDetail.y = (self.height - _productDetail.height); } and here is the code I found... float pulsesteps[3] = { 0.2, 1/15., 1/7.5 }; - (void) pulse { self.transform = CGAffineTransformMakeScale(0.6, 0.6); [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:pulsesteps[0]]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(pulseGrowAnimationDidStop:finished:context:)]; self.transform = CGAffineTransformMakeScale(1.1, 1.1); [UIView commitAnimations]; } - (void)pulseGrowAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:pulsesteps[1]]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(pulseShrinkAnimationDidStop:finished:context:)]; self.transform = CGAffineTransformMakeScale(0.9, 0.9); [UIView commitAnimations]; } - (void)pulseShrinkAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:pulsesteps[2]]; self.transform = CGAffineTransformIdentity; [UIView commitAnimations]; } My routine is based on the Prototyping class given by Apple during WWDC 09. It may not be "correct" but it works as is. I just would like to add the animation to this image/screen to really make the concept clear.

    Read the article

  • Blending the Sketchflow Action

    - by GeekAgilistMercenary
    Started a new Sketchflow Prototype in Expression Blend recently and documented each of the steps.  This blog entry covers some of those steps, which are the basic elements of any prototype.  I will have more information regarding design, prototype creation, and the process of the initial phases for development in the future.  For now, I hope you enjoy this short walk through.  Also, be sure to check out my last quick entry on Sketchflow. I started off with a Sketchflow Project, just like I did in my previous entry (more specifics in that entry about how to manipulate and build out the Sketchflow Map). Once I created the project I setup the following Sketchflow Map. The CoreNavigation is a ComponentScreen setup solely for the page navigation at the top of the screen.  The XAML markup in case you want to create a Component Screen with the same design is included below. <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:pb="clr-namespace:Microsoft.Expression.Prototyping.Behavior;assembly=Microsoft.Expression.Prototyping.Interactivity" x:Class="RapidPrototypeSketchScreens.CoreNavigation" d:DesignWidth="624" d:DesignHeight="49" Height="49" Width="624">   <Grid x:Name="LayoutRoot"> <TextBlock HorizontalAlignment="Stretch" Margin="307,3,0,0" Style="{StaticResource TitleCenter-Sketch}" Text="Aütøchart Scorecards" TextWrapping="Wrap"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <pb:NavigateToScreenAction TargetScreen="RapidPrototypeSketchScreens.Screen_1"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBlock> <Button HorizontalAlignment="Left" Margin="164,8,0,11" Style="{StaticResource Button-Sketch}" Width="144" Content="Scorecard"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <pb:NavigateToScreenAction TargetScreen="RapidPrototypeSketchScreens.Screen_1_2"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> <Button HorizontalAlignment="Left" Margin="8,8,0,11" Style="{StaticResource Button-Sketch}" Width="152" Content="Standard Reports"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <pb:NavigateToScreenAction TargetScreen="RapidPrototypeSketchScreens.Screen_1_1"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> </Grid> </UserControl> Now that the CoreNavigation Component Screen is done I built out each of the others.  In each of those screens I included the CoreNavigation Screen (all those little green lines in the image) as the top navigation.  In order to do that, as I created each of the pages I would hover over the CoreNavigation Object in the Sketchflow Map.  When the utilities drawer (the small menu that pops down under a node when you hover over it) shows click on the third little icon and drag it onto the page node you want a navigation screen on. Once I created all the screens I setup the navigation by opening up each screen and right clicking on the objects that needed to point to somewhere else in the prototype. Once I was done with the main page, my Home Navigation Page, it looked something like this in the Expression Blend Designer. I fleshed out each of the additional screens.  Once I was done I wanted to try out the deployment package.  The way to deploy a Sketchflow Prototype is to merely click on File –> Package SketchFlow Project and a prompt will appear.  In the prompt enter what you want the package to be called. I like to see the files generated afterwards too, so I checked the box to see that.  When Expression Blend is done generating everything you’ll have a directory like the one shown below, with all the needed files for deployment. Now these files can be copied or moved to any location for viewing.  One can even copy them (such as via FTP) to a server location to share with others.  Once they are deployed and you run the "TestPage.html" the other features of the Sketchflow Package are available. In the image below I have tagged a few sections to show the Sketchflow Player Features.  To the top left is the navigation, which provides a clearly defined area of movement in a list.  To the center right is the actual prototype application.  I have placed lists of things and made edits.  On the left hand side is the highlight feature, which is available in the Feedback section of the lower left.  On the right hand list I underlined the Autochart with an orange marker, and marked out two list items with a red marker. In the lower left hand side in the Feedback section is also an area to type in your feedback.  This can be useful for time based feedback, when you post this somewhere and want people to provide subsequent follow up feedback. Overall lots of great features, that enable some fairly rapid prototyping with customers.  Once one is familiar with the steps and parts of this Sketchflow Prototype Capabilities it is easy to step through an application without even stopping.  It really is that easy.  So get hold of Expression Blend 3 and get ramped up on Sketchflow, it will pay off in the design phases to do so! Original Entry

    Read the article

  • JavaScript Class Patterns

    - by Liam McLennan
    To write object-oriented programs we need objects, and likely lots of them. JavaScript makes it easy to create objects: var liam = { name: "Liam", age: Number.MAX_VALUE }; But JavaScript does not provide an easy way to create similar objects. Most object-oriented languages include the idea of a class, which is a template for creating objects of the same type. From one class many similar objects can be instantiated. Many patterns have been proposed to address the absence of a class concept in JavaScript. This post will compare and contrast the most significant of them. Simple Constructor Functions Classes may be missing but JavaScript does support special constructor functions. By prefixing a call to a constructor function with the ‘new’ keyword we can tell the JavaScript runtime that we want the function to behave like a constructor and instantiate a new object containing the members defined by that function. Within a constructor function the ‘this’ keyword references the new object being created -  so a basic constructor function might be: function Person(name, age) { this.name = name; this.age = age; this.toString = function() { return this.name + " is " + age + " years old."; }; } var john = new Person("John Galt", 50); console.log(john.toString()); Note that by convention the name of a constructor function is always written in Pascal Case (the first letter of each word is capital). This is to distinguish between constructor functions and other functions. It is important that constructor functions be called with the ‘new’ keyword and that not constructor functions are not. There are two problems with the pattern constructor function pattern shown above: It makes inheritance difficult The toString() function is redefined for each new object created by the Person constructor. This is sub-optimal because the function should be shared between all of the instances of the Person type. Constructor Functions with a Prototype JavaScript functions have a special property called prototype. When an object is created by calling a JavaScript constructor all of the properties of the constructor’s prototype become available to the new object. In this way many Person objects can be created that can access the same prototype. An improved version of the above example can be written: function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { toString: function() { return this.name + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); In this version a single instance of the toString() function will now be shared between all Person objects. Private Members The short version is: there aren’t any. If a variable is defined, with the var keyword, within the constructor function then its scope is that function. Other functions defined within the constructor function will be able to access the private variable, but anything defined outside the constructor (such as functions on the prototype property) won’t have access to the private variable. Any variables defined on the constructor are automatically public. Some people solve this problem by prefixing properties with an underscore and then not calling those properties by convention. function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { _getName: function() { return this.name; }, toString: function() { return this._getName() + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); Note that the _getName() function is only private by convention – it is in fact a public function. Functional Object Construction Because of the weirdness involved in using constructor functions some JavaScript developers prefer to eschew them completely. They theorize that it is better to work with JavaScript’s functional nature than to try and force it to behave like a traditional class-oriented language. When using the functional approach objects are created by returning them from a factory function. An excellent side effect of this pattern is that variables defined with the factory function are accessible to the new object (due to closure) but are inaccessible from anywhere else. The Person example implemented using the functional object construction pattern is: var personFactory = function(name, age) { var privateVar = 7; return { toString: function() { return name + " is " + age * privateVar / privateVar + " years old."; } }; }; var john2 = personFactory("John Lennon", 40); console.log(john2.toString()); Note that the ‘new’ keyword is not used for this pattern, and that the toString() function has access to the name, age and privateVar variables because of closure. This pattern can be extended to provide inheritance and, unlike the constructor function pattern, it supports private variables. However, when working with JavaScript code bases you will find that the constructor function is more common – probably because it is a better approximation of mainstream class oriented languages like C# and Java. Inheritance Both of the above patterns can support inheritance but for now, favour composition over inheritance. Summary When JavaScript code exceeds simple browser automation object orientation can provide a powerful paradigm for controlling complexity. Both of the patterns presented in this article work – the choice is a matter of style. Only one question still remains; who is John Galt?

    Read the article

  • JavaScript Class Patterns

    - by Liam McLennan
    To write object-oriented programs we need objects, and likely lots of them. JavaScript makes it easy to create objects: var liam = { name: "Liam", age: Number.MAX_VALUE }; But JavaScript does not provide an easy way to create similar objects. Most object-oriented languages include the idea of a class, which is a template for creating objects of the same type. From one class many similar objects can be instantiated. Many patterns have been proposed to address the absence of a class concept in JavaScript. This post will compare and contrast the most significant of them. Simple Constructor Functions Classes may be missing but JavaScript does support special constructor functions. By prefixing a call to a constructor function with the ‘new’ keyword we can tell the JavaScript runtime that we want the function to behave like a constructor and instantiate a new object containing the members defined by that function. Within a constructor function the ‘this’ keyword references the new object being created -  so a basic constructor function might be: function Person(name, age) { this.name = name; this.age = age; this.toString = function() { return this.name + " is " + age + " years old."; }; } var john = new Person("John Galt", 50); console.log(john.toString()); Note that by convention the name of a constructor function is always written in Pascal Case (the first letter of each word is capital). This is to distinguish between constructor functions and other functions. It is important that constructor functions be called with the ‘new’ keyword and that not constructor functions are not. There are two problems with the pattern constructor function pattern shown above: It makes inheritance difficult The toString() function is redefined for each new object created by the Person constructor. This is sub-optimal because the function should be shared between all of the instances of the Person type. Constructor Functions with a Prototype JavaScript functions have a special property called prototype. When an object is created by calling a JavaScript constructor all of the properties of the constructor’s prototype become available to the new object. In this way many Person objects can be created that can access the same prototype. An improved version of the above example can be written: function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { toString: function() { return this.name + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); In this version a single instance of the toString() function will now be shared between all Person objects. Private Members The short version is: there aren’t any. If a variable is defined, with the var keyword, within the constructor function then its scope is that function. Other functions defined within the constructor function will be able to access the private variable, but anything defined outside the constructor (such as functions on the prototype property) won’t have access to the private variable. Any variables defined on the constructor are automatically public. Some people solve this problem by prefixing properties with an underscore and then not calling those properties by convention. function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { _getName: function() { return this.name; }, toString: function() { return this._getName() + " is " + this.age + " years old."; } }; var john = new Person("John Galt", 50); console.log(john.toString()); Note that the _getName() function is only private by convention – it is in fact a public function. Functional Object Construction Because of the weirdness involved in using constructor functions some JavaScript developers prefer to eschew them completely. They theorize that it is better to work with JavaScript’s functional nature than to try and force it to behave like a traditional class-oriented language. When using the functional approach objects are created by returning them from a factory function. An excellent side effect of this pattern is that variables defined with the factory function are accessible to the new object (due to closure) but are inaccessible from anywhere else. The Person example implemented using the functional object construction pattern is: var john = new Person("John Galt", 50); console.log(john.toString()); var personFactory = function(name, age) { var privateVar = 7; return { toString: function() { return name + " is " + age * privateVar / privateVar + " years old."; } }; }; var john2 = personFactory("John Lennon", 40); console.log(john2.toString()); Note that the ‘new’ keyword is not used for this pattern, and that the toString() function has access to the name, age and privateVar variables because of closure. This pattern can be extended to provide inheritance and, unlike the constructor function pattern, it supports private variables. However, when working with JavaScript code bases you will find that the constructor function is more common – probably because it is a better approximation of mainstream class oriented languages like C# and Java. Inheritance Both of the above patterns can support inheritance but for now, favour composition over inheritance. Summary When JavaScript code exceeds simple browser automation object orientation can provide a powerful paradigm for controlling complexity. Both of the patterns presented in this article work – the choice is a matter of style. Only one question still remains; who is John Galt?

    Read the article

  • Javascript Prototyping Question

    - by Nick Lowman
    I'm just reading about Prototypes in JavaScript and Douglas Crockford offers and excellent way to select a new objects prototype but can anyone explain (below) why obj01's type equals 'object' when I pass it in function as it's prototype? if (typeof Object.beget !== 'function') { Object.beget = function (o) { console.log(typeof o);//function var F = function () {}; F.prototype = o; console.log(typeof F);//function return new F(); }; } var func01 = function(){}; var obj01 = Object.beget(func01); console.log(typeof obj01);//object console.log(typeof obj01.prototype);//object I thought it would be console.log(typeof obj01);//function console.log(typeof obj01.prototype);//function

    Read the article

  • i want to call the function when i clicked on the checkbox using prototype.js.here obj[i] contents j

    - by vicky
    DeCheBX = $('MyDiv').insert(new Element('input', { 'type': 'checkbox', 'id': "Img" + obj[i].Nam, 'value': obj[i].IM, 'onClick': SayHi(this) })); document.body.appendChild(DeCheBX); DeImg = $('MyDiv').insert(new Element('img', { 'id': "Imgx" + obj[i].Nam, 'src': obj[i].IM })); document.body.appendChild(DeImg); } SayHi = function(x) { try { if($(x).checked == true) { alert("press" + x); } } catch (e) { alert("error");

    Read the article

  • add html after a certain div - using prototype? How

    - by Ali
    Hi guys I want to be able to append divs to my page such that they are appended after a div of a certain class and before teh divs that follow it i.e: <div class="header">Header DIV</div> <!-- Want to add using javascript some HTML right here--> <div class="one-basic-div">...</div> <div class="one-basic-div">...</div> <div class="one-basic-div">...</div> <div class="one-basic-div">...</div> Its basically raw html I wish to add - how can I do it.

    Read the article

  • How I pass a delegate prototype to a method?

    - by Jeff Dahmer
    SO lets say in my class I have: public delegate bool MyFunc(int param); How can I then do this someObj.PassMeADelegateToExamine(this.MyFunc); // not possible!?! SO that I can examine the delegate and perhaps use reflection or something idk to find out it's return type and any params it might have? Basically if I can transform it into an (uncallable) Action object that woul dbe grand

    Read the article

  • Prototype Ajax.Updater Response OK, but not showing up in FF. working in Safari!

    - by koko
    Hi, I've got a quite strange problem here. I'm calling some simple code via Ajax.Updater: new Ajax.Updater('load','http://myurl.com/demo.pl?key=demokey&param1=xyz&param2=abc',{ method:'get', onComplete:function(transport){ alert(transport.responseText) } }); which gets some code like this: <img id="2009_04_15_1239786246" src='../pv/100/2009_04_15_1239786246-01.jpg' border="1"> <img id="2009_04_15_1239786066" src='../pv/100/2009_04_15_1239786066-01.jpg' border="1"> ... and so on This code shows up in my firebug console as my server response, so everything should be fine. No errors here at all. Works fine in Safari. Firefox, according to Firebug, knows there is a response, but it won't show a thing in my div 'load' and the alert(transport.responseText) is also empty. I have no idea what could be the problem here.

    Read the article

  • why does $().invokde('hide')doesnt work?what is used to hide image in prototype.js?

    - by vicky
    DeCheBX = $('MyDiv').insert(new Element('input', { 'type': 'checkbox', 'id': "Img" + obj[i].Nam, 'value': obj[i].IM, 'onClick': 'SayHi(this)' })); document.body.appendChild(DeCheBX); DeImg = $('MyDiv').insert(new Element('img', { 'id': "Imgx" + obj[i].Nam, 'src': obj[i].IM })); document.body.appendChild(DeImg); } SayHi = function(x) { try { if ($(x).checked == true) { var y = "Imgx" + 1; alert(y); $('y').invoke('hide');

    Read the article

  • Find the exact height and width of the viewport in a cross-browser way (no Prototype/jQuery)

    - by lyoshenka
    I'm trying to find the exact height and width of a browser's viewport, but I suspect that either Mozilla or IE is giving me the wrong number. Here's my method for height: var viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; I haven't started on width yet but I'm guessing it's going to be something similar. Is there a more correct way of getting this information? Ideally, I'd like the solution to work with Safari/Chrome/other browsers as well.

    Read the article

  • What should I put in the href when I prototype?

    - by David
    When protyping we often do empty anchors. A very common way to do this is to do something like: <a href="#">Go here</a> But if the client clicks this link, the page will scroll to the top. But if we leave out the href attribute, the link won't behave like a link. I've see stuff like: <a href="javascript;">Go here</a> But it doesn't look right. Any other ideas?

    Read the article

  • Avoiding new operator in JavaScript -- the better way

    - by greengit
    Warning: This is a long post. Let's keep it simple. I want to avoid having to prefix the new operator every time I call a constructor in JavaScript. This is because I tend to forget it, and my code screws up badly. The simple way around this is this... function Make(x) { if ( !(this instanceof arguments.callee) ) return new arguments.callee(x); // do your stuff... } But, I need this to accept variable no. of arguments, like this... m1 = Make(); m2 = Make(1,2,3); m3 = Make('apple', 'banana'); The first immediate solution seems to be the 'apply' method like this... function Make() { if ( !(this instanceof arguments.callee) ) return new arguments.callee.apply(null, arguments); // do your stuff } This is WRONG however -- the new object is passed to the apply method and NOT to our constructor arguments.callee. Now, I've come up with three solutions. My simple question is: which one seems best. Or, if you have a better method, tell it. First – use eval() to dynamically create JavaScript code that calls the constructor. function Make(/* ... */) { if ( !(this instanceof arguments.callee) ) { // collect all the arguments var arr = []; for ( var i = 0; arguments[i]; i++ ) arr.push( 'arguments[' + i + ']' ); // create code var code = 'new arguments.callee(' + arr.join(',') + ');'; // call it return eval( code ); } // do your stuff with variable arguments... } Second – Every object has __proto__ property which is a 'secret' link to its prototype object. Fortunately this property is writable. function Make(/* ... */) { var obj = {}; // do your stuff on 'obj' just like you'd do on 'this' // use the variable arguments here // now do the __proto__ magic // by 'mutating' obj to make it a different object obj.__proto__ = arguments.callee.prototype; // must return obj return obj; } Third – This is something similar to second solution. function Make(/* ... */) { // we'll set '_construct' outside var obj = new arguments.callee._construct(); // now do your stuff on 'obj' just like you'd do on 'this' // use the variable arguments here // you have to return obj return obj; } // now first set the _construct property to an empty function Make._construct = function() {}; // and then mutate the prototype of _construct Make._construct.prototype = Make.prototype; eval solution seems clumsy and comes with all the problems of "evil eval". __proto__ solution is non-standard and the "Great Browser of mIsERY" doesn't honor it. The third solution seems overly complicated. But with all the above three solutions, we can do something like this, that we can't otherwise... m1 = Make(); m2 = Make(1,2,3); m3 = Make('apple', 'banana'); m1 instanceof Make; // true m2 instanceof Make; // true m3 instanceof Make; // true Make.prototype.fire = function() { // ... }; m1.fire(); m2.fire(); m3.fire(); So effectively the above solutions give us "true" constructors that accept variable no. of arguments and don't require new. What's your take on this. -- UPDATE -- Some have said "just throw an error". My response is: we are doing a heavy app with 10+ constructors and I think it'd be far more wieldy if every constructor could "smartly" handle that mistake without throwing error messages on the console.

    Read the article

  • How to override part of an overload function in JavaScript

    - by Guan Yuxin
    I create a class with a function like this var Obj=function(){this.children=[];this.parent=null;}//a base class Obj.prototype.index=function(child){ // the index of current obj if(arguments.length==0){ return this.parent?this.parent.index(this):0; } // the index of a child matchs specific obj [to be override] return -1; } basically it is just an overload function composed of index() and index(child). Then I create a sub class,SubObj or whatever, inherits from Obj SubObj.prototype.prototype=Obj; Now, it's time to override the index(child) function,however, index() is also in the function an I don't want to overwrite it too. One solution is to write like this var Obj=function(){this.children=[];this.parent=null;}//a base class Obj.prototype.index=function(child){ // the index of current obj if(arguments.length==0){ return this.parent?this.parent.index(this):0; } // the index of a child matchs specific obj [to be override] return this._index(this); } Obj.prototype._index=function(this){ return -1; } SubObj.prototype._index=function(this){/* overwriteing */} But this will easily mislead other coders as _index(child) should be both private(should not be used except index() function) and public(is an overload function of index(),which is public) you guys have better idea?

    Read the article

  • WebCenter Spaces 11g PS2 Template Customization

    - by javier.ductor(at)oracle.com
    Recently, we have been involved in a WebCenter Spaces customization project. Customer sent us a prototype website in HTML, and we had to transform Spaces to set the same look&feel as in the prototype.Protoype:First of all, we downloaded a Virtual Machine with WebCenter Spaces 11g PS2, same version as customer's. The next step was to download ExtendWebCenterSpaces application. This is a webcenter application that customizes several elements of WebCenter Spaces: templates, skins, landing page, etc. jDeveloper configuration is needed, we followed steps described in Extended Guide, this blog was helpful too. . After that, we deployed the application using WebLogic console, we created a new group space and assigned the ExtendedWebCenterSpaces template (portalCentricSiteTemplate) to it. The result was this:As you may see there is a big difference with the prototype, which meant a lot of work to do from our side.So we needed to create a new Spaces template with its skin.Using jDeveloper, we created a new template based on the default template. We removed all menus we did not need and inserted 'include'  tags for header, breadcrumb and footers. Each of these elements was defined in an isolated jspx file.In the beginning, we faced a problem: we had to add code from prototype (in plain HTML) to jspx templates (JSF language). We managed to workaround this issue using 'verbatim' tags with 'CDATA' surrounding HTML code in header, breadcrumb and footers.Once the template was modified, we added css styles to the default skin. So we had some styles from portalCentricSiteTemplate plus styles from customer's prototype.Then, we re-deployed the application, assigned this template to a new group space and checked the result. After testing, we usually found issues, so we had to do some modifications in the application, then it was necessary to re-deploy the application and restart Spaces server. Due to this fact, the testing process takes quite a bit of time.Added to the template and skin customization, we also customized the Landing Page using this application and Members task flow using another application: SpacesTaskflowCustomizationApplication. I will talk about this task flow customization in a future entry.After some issues and workarounds, eventually we managed to get this look&feel in Spaces:P.S. In this customization I was working with Francisco Vega and Jose Antonio Labrada, consultants from Oracle Malaga International Consulting Centre.

    Read the article

  • Creating classed in JavaScript

    - by Renso
    Goal:Creating class instances in JavaScript is not available since you define "classes" in js with object literals. In order to create classical classes like you would in c#, ruby, java, etc, with inheritance and instances.Rather than typical class definitions using object literals, js has a constructor function and the NEW operator that will allow you to new-up a class and optionally provide initial properties to initialize the new object with.The new operator changes the function's context and behavior of the return statement.var Person = function(name) {   this.name = name;};   //Init the personvar dude= new Person("renso");//Validate the instanceassert(dude instanceof Person);When a constructor function is called with the new keyword, the context changes from global window to a new and empty context specific to the instance; "this" will refer in this case to the "dude" context.Here is class pattern that you will need to define your own CLASS emulation library:var Class = function() {   var _class = function() {      this.init.apply(this, arguments);   };   _class.prototype.init = function(){};   return _class;}var Person a new Class();Person.prototype.init = function() {};var person = new Person;In order for the class emulator to support adding functions and properties to static classes as well as object instances of People, change the emulator:var Class = function() {   var _class = function() {      this.init.apply(this, arguments);   };   _class.prototype.init = function(){};   _class.fn = _class.prototype;   _class.fn.parent = _class;   //adding class properties   _class.extend = function(obj) {      var extended = obj.extended;      for(var i in obj) {         _class[i] = obj[i];      };      if(extended) extended(_class);   };   //adding new instances   _class.include = function(obj) {      var included = obj.included;      for(var i in obj) {         _class.fn[i] = obj[i];      };      if(included) included(_class);   };   return _class;}Now you can use it to create and extend your own object instances://adding static functions to the class Personvar Person = new Class();Person.extend({   find: function(name) {/*....*/},      delete: function(id) {/*....*/},});//calling static function findvar person = Person.find('renso');   //adding properties and functions to the class' prototype so that they are available on instances of the class Personvar Person = new Class;Person.extend({   save: function(name) {/*....*/},   delete: function(id) {/*....*/}});var dude = new Person;//calling instance functiondude.save('renso');

    Read the article

  • How to write a ~/.firefoxrc?

    - by kev
    I want firefox sources ~/.firefoxrc automatically when I open a webpage. ~/.firefoxrc contains several javascript functions: Array.prototype.sum = function(){ for(var i=0,sum=0;i<this.length;sum+=this[i++]); return sum; } Array.prototype.max = function(){ return Math.max.apply({},this) } Array.prototype.min = function(){ return Math.min.apply({},this) } So I can use these functions in firebug console.

    Read the article

  • jQuery Templates and Data Linking (and Microsoft contributing to jQuery)

    - by ScottGu
    The jQuery library has a passionate community of developers, and it is now the most widely used JavaScript library on the web today. Two years ago I announced that Microsoft would begin offering product support for jQuery, and that we’d be including it in new versions of Visual Studio going forward. By default, when you create new ASP.NET Web Forms and ASP.NET MVC projects with VS 2010 you’ll find jQuery automatically added to your project. A few weeks ago during my second keynote at the MIX 2010 conference I announced that Microsoft would also begin contributing to the jQuery project.  During the talk, John Resig -- the creator of the jQuery library and leader of the jQuery developer team – talked a little about our participation and discussed an early prototype of a new client templating API for jQuery. In this blog post, I’m going to talk a little about how my team is starting to contribute to the jQuery project, and discuss some of the specific features that we are working on such as client-side templating and data linking (data-binding). Contributing to jQuery jQuery has a fantastic developer community, and a very open way to propose suggestions and make contributions.  Microsoft is following the same process to contribute to jQuery as any other member of the community. As an example, when working with the jQuery community to improve support for templating to jQuery my team followed the following steps: We created a proposal for templating and posted the proposal to the jQuery developer forum (http://forum.jquery.com/topic/jquery-templates-proposal and http://forum.jquery.com/topic/templating-syntax ). After receiving feedback on the forums, the jQuery team created a prototype for templating and posted the prototype at the Github code repository (http://github.com/jquery/jquery-tmpl ). We iterated on the prototype, creating a new fork on Github of the templating prototype, to suggest design improvements. Several other members of the community also provided design feedback by forking the templating code. There has been an amazing amount of participation by the jQuery community in response to the original templating proposal (over 100 posts in the jQuery forum), and the design of the templating proposal has evolved significantly based on community feedback. The jQuery team is the ultimate determiner on what happens with the templating proposal – they might include it in jQuery core, or make it an official plugin, or reject it entirely.  My team is excited to be able to participate in the open source process, and make suggestions and contributions the same way as any other member of the community. jQuery Template Support Client-side templates enable jQuery developers to easily generate and render HTML UI on the client.  Templates support a simple syntax that enables either developers or designers to declaratively specify the HTML they want to generate.  Developers can then programmatically invoke the templates on the client, and pass JavaScript objects to them to make the content rendered completely data driven.  These JavaScript objects can optionally be based on data retrieved from a server. Because the jQuery templating proposal is still evolving in response to community feedback, the final version might look very different than the version below. This blog post gives you a sense of how you can try out and use templating as it exists today (you can download the prototype by the jQuery core team at http://github.com/jquery/jquery-tmpl or the latest submission from my team at http://github.com/nje/jquery-tmpl).  jQuery Client Templates You create client-side jQuery templates by embedding content within a <script type="text/html"> tag.  For example, the HTML below contains a <div> template container, as well as a client-side jQuery “contactTemplate” template (within the <script type="text/html"> element) that can be used to dynamically display a list of contacts: The {{= name }} and {{= phone }} expressions are used within the contact template above to display the names and phone numbers of “contact” objects passed to the template. We can use the template to display either an array of JavaScript objects or a single object. The JavaScript code below demonstrates how you can render a JavaScript array of “contact” object using the above template. The render() method renders the data into a string and appends the string to the “contactContainer” DIV element: When the page is loaded, the list of contacts is rendered by the template.  All of this template rendering is happening on the client-side within the browser:   Templating Commands and Conditional Display Logic The current templating proposal supports a small set of template commands - including if, else, and each statements. The number of template commands was deliberately kept small to encourage people to place more complicated logic outside of their templates. Even this small set of template commands is very useful though. Imagine, for example, that each contact can have zero or more phone numbers. The contacts could be represented by the JavaScript array below: The template below demonstrates how you can use the if and each template commands to conditionally display and loop the phone numbers for each contact: If a contact has one or more phone numbers then each of the phone numbers is displayed by iterating through the phone numbers with the each template command: The jQuery team designed the template commands so that they are extensible. If you have a need for a new template command then you can easily add new template commands to the default set of commands. Support for Client Data-Linking The ASP.NET team recently submitted another proposal and prototype to the jQuery forums (http://forum.jquery.com/topic/proposal-for-adding-data-linking-to-jquery). This proposal describes a new feature named data linking. Data Linking enables you to link a property of one object to a property of another object - so that when one property changes the other property changes.  Data linking enables you to easily keep your UI and data objects synchronized within a page. If you are familiar with the concept of data-binding then you will be familiar with data linking (in the proposal, we call the feature data linking because jQuery already includes a bind() method that has nothing to do with data-binding). Imagine, for example, that you have a page with the following HTML <input> elements: The following JavaScript code links the two INPUT elements above to the properties of a JavaScript “contact” object that has a “name” and “phone” property: When you execute this code, the value of the first INPUT element (#name) is set to the value of the contact name property, and the value of the second INPUT element (#phone) is set to the value of the contact phone property. The properties of the contact object and the properties of the INPUT elements are also linked – so that changes to one are also reflected in the other. Because the contact object is linked to the INPUT element, when you request the page, the values of the contact properties are displayed: More interesting, the values of the linked INPUT elements will change automatically whenever you update the properties of the contact object they are linked to. For example, we could programmatically modify the properties of the “contact” object using the jQuery attr() method like below: Because our two INPUT elements are linked to the “contact” object, the INPUT element values will be updated automatically (without us having to write any code to modify the UI elements): Note that we updated the contact object above using the jQuery attr() method. In order for data linking to work, you must use jQuery methods to modify the property values. Two Way Linking The linkBoth() method enables two-way data linking. The contact object and INPUT elements are linked in both directions. When you modify the value of the INPUT element, the contact object is also updated automatically. For example, the following code adds a client-side JavaScript click handler to an HTML button element. When you click the button, the property values of the contact object are displayed using an alert() dialog: The following demonstrates what happens when you change the value of the Name INPUT element and click the Save button. Notice that the name property of the “contact” object that the INPUT element was linked to was updated automatically: The above example is obviously trivially simple.  Instead of displaying the new values of the contact object with a JavaScript alert, you can imagine instead calling a web-service to save the object to a database. The benefit of data linking is that it enables you to focus on your data and frees you from the mechanics of keeping your UI and data in sync. Converters The current data linking proposal also supports a feature called converters. A converter enables you to easily convert the value of a property during data linking. For example, imagine that you want to represent phone numbers in a standard way with the “contact” object phone property. In particular, you don’t want to include special characters such as ()- in the phone number - instead you only want digits and nothing else. In that case, you can wire-up a converter to convert the value of an INPUT element into this format using the code below: Notice above how a converter function is being passed to the linkFrom() method used to link the phone property of the “contact” object with the value of the phone INPUT element. This convertor function strips any non-numeric characters from the INPUT element before updating the phone property.  Now, if you enter the phone number (206) 555-9999 into the phone input field then the value 2065559999 is assigned to the phone property of the contact object: You can also use a converter in the opposite direction also. For example, you can apply a standard phone format string when displaying a phone number from a phone property. Combining Templating and Data Linking Our goal in submitting these two proposals for templating and data linking is to make it easier to work with data when building websites and applications with jQuery. Templating makes it easier to display a list of database records retrieved from a database through an Ajax call. Data linking makes it easier to keep the data and user interface in sync for update scenarios. Currently, we are working on an extension of the data linking proposal to support declarative data linking. We want to make it easy to take advantage of data linking when using a template to display data. For example, imagine that you are using the following template to display an array of product objects: Notice the {{link name}} and {{link price}} expressions. These expressions enable declarative data linking between the SPAN elements and properties of the product objects. The current jQuery templating prototype supports extending its syntax with custom template commands. In this case, we are extending the default templating syntax with a custom template command named “link”. The benefit of using data linking with the above template is that the SPAN elements will be automatically updated whenever the underlying “product” data is updated.  Declarative data linking also makes it easier to create edit and insert forms. For example, you could create a form for editing a product by using declarative data linking like this: Whenever you change the value of the INPUT elements in a template that uses declarative data linking, the underlying JavaScript data object is automatically updated. Instead of needing to write code to scrape the HTML form to get updated values, you can instead work with the underlying data directly – making your client-side code much cleaner and simpler. Downloading Working Code Examples of the Above Scenarios You can download this .zip file to get with working code examples of the above scenarios.  The .zip file includes 4 static HTML page: Listing1_Templating.htm – Illustrates basic templating. Listing2_TemplatingConditionals.htm – Illustrates templating with the use of the if and each template commands. Listing3_DataLinking.htm – Illustrates data linking. Listing4_Converters.htm – Illustrates using a converter with data linking. You can un-zip the file to the file-system and then run each page to see the concepts in action. Summary We are excited to be able to begin participating within the open-source jQuery project.  We’ve received lots of encouraging feedback in response to our first two proposals, and we will continue to actively contribute going forward.  These features will hopefully make it easier for all developers (including ASP.NET developers) to build great Ajax applications. Hope this helps, Scott P.S. [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

    Read the article

  • Are super methods in JavaScript limited to functional inheritance, as per Crockford's book?

    - by kindohm
    In Douglas Crockford's "JavaScript: The Good Parts", he walks through three types of inheritance: classical, prototypal, and functional. In the part on functional inheritance he writes: "The functional pattern also gives us a way to deal with super methods." He then goes on to implement a method named "superior" on all Objects. However, in the way he uses the superior method, it just looks like he is copying the method on the super object for later use: // crockford's code: var coolcat = function(spec) { var that = cat(spec), super_get_name = that.superior('get_name'); that.get_name = function (n) { return 'like ' + super_get_name() + ' baby'; }; return that; }; The original get_name method is copied to super_get_name. I don't get what's so special about functional inheritance that makes this possible. Can't you do this with classical or prototypal inheritance? What's the difference between the code above and the code below: var CoolCat = function(name) { this.name = name; } CoolCat.prototype = new Cat(); CoolCat.prototype.super_get_name = CoolCat.prototype.get_name; CoolCat.prototype.get_name = function (n) { return 'like ' + this.super_get_name() + ' baby'; }; Doesn't this second example provide access to "super methods" too?

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >