Swift passing element as variable - javascript

In javascript I know i can something like the following:
var foo = '';
function changeVariable(variable, data){
this[variable] = data;
}
changeVariable("foo", "bar");
Is there away I can do this in swift?
func toggleFadeIn (element: String, active: Bool)
{
if(!active){
self.element.alpha = 0;
self.element.transform = CGAffineTransform(translationX: 0, y: 25)
}
}

Javascript is a dynamic language that has the facilities of modifying objects in such a way at runtime.
Static languages (like Swift, Java, C#, and many others) require a reflection library to implement such behaviour. Unfortunately, Swift has a really limited reflection capability (Mirror) and doesn't have the ability to modify object/struct members by their String names, yet.
If you elaborate on what exactly you were trying to achieve with this, we would be better able to suggest solutions.

What you describe IS possible using KVO on NSObjects. It relies on Objective-C dynamic messaging, but it does work. Take a look a the function setValue:forKey:, as documented in Apple's Key Value Programming Guide.
Note that this is decidedly un-swiftlike, and not recommended.

Related

When should I use data type classes in JavaScript

I come from a C# background. I've been working a lot with JavaScript lately. On a new app, I have a mysql/php back end. I'm going to be passing a lot of "types" back and forth.
So in my data base, I have several tables like
table1
id, fieldx,fieldy,fieldz
table2
id, fielda,fieldb,fielc
In c# I would definitely write classes for all those in the code. Which led me to implement things like so (in my JavaScript app):
function table1(id, x,y,z){
this.id=id;
this.x=x;
this.y=y;
this.z=z;
}
After about 6 tables worth of that, it suddenly occurred to me that maybe there was no point at all in making these classes.
So my question is, in a JavaScript app, do I use "classes" for data types? or should I just "document" which fields/types are expected and so in the code instead of
a.push(new table1(5,1,2,3));
I would just have
a.push({id:5,x:1,y:2,z:3});
This may seem like a preferences question but it's a fundamental language question that I have as I try to understand how to model my app's data in JavaScript. Is there any advantage of the classes (with only data fields) or is it just a mistake. Thanks.
It depends,
Note: Most of the programmers coming from a strong OO language will have trouble like you in regard to JavaScript's functional behavior (you are not alone).
If you want to create something closer to C# I would do the following:
function Table1(id, x, y, z) {
this.id=id;
this.x=x;
this.y=y;
this.z=z;
}
Table1.prototype.mySpecialTable1Method= function()
{
console.log(this.id);
};
Implementation:
var t = new Table1(1, 2, 3, 4);
t.mySpecialTable1Method();// outputs: 1
If you need to have methods that interact with the (soon to be) objects then I would definitely go with the code above. In addition it will make it clear when working with the objects that are related to a specific 'type' (naming the data).
But if your objects do not require any special "treatment" then I don't see any problem to use normal js object literals and pass them along (probably good for small projects).
Something along the lines:
var table1 = {};
table1.id = 1;
table1.x = 2;
table1.y = 3;
table1.z = 4;
console.log(table1.id); //outputs: 1
Extra reference:
http://www.youtube.com/watch?v=PMfcsYzj-9M
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Update:
For the sake of readability and scalability and the point that you are coming from C# you may want to stick to the "class" implementation just because it will define the correlation between the raw data and the objects you are working with.
There is a good chance that you are going to work with some data that will probably be messy and unorganized.
MVC may be the solution for you. It tries to bring some order to the chaos that you are expecting. I recommend to check out some of them like: AngularJS or Ember.
Another solution may be reactive js - but mostly if you are going to interact with the DOM according to your data (ReactJS, and Facebook's React as some good ones).
As a note for security, I would like to add that mapping the data closely to the db isn't a best practice but its your call.
Javascript is a funny language, and there are plenty of ways to do things. An Object is an Object in Javascript with or without a name. {} is just a short-hand way to create one.
If you are going for readability, then your initial example would be the way to go.
If you just want to get the block of data into an array, then your second example is appropriate. Personally, I would use your later example if it is just data.
If you are using functions and what not as well as data storage, and plan on reusing it several times in your code, then yes, define your object and call it appropriately.
JavaScript has no classes, it is a functional language and a function is a first class citizen in js meaning that a function is an object.
From your example I can see that your intention for classes is simply to pass data and using json is perfect for this.

Approach to using TypeScript descriptor files, such as Knockout.d.ts

I have just been looking over some of the examples from
https://github.com/borisyankov/DefinitelyTyped
And noticed that some of the libraries in there were not as easy to just pick up and use as I thought, but this is probably because I am still a newcomer to the TypeScript show.
So the first thing that struck me as off (using Knockout as the example here), none of it is included within a module, which I dont really think is a major issue probably more a design decision by whoever made it, but it seemed like it would make more sense (possibly because I tend to do more C# than other languages) because it would be self contained and easier to include other plugins under the namespace:
i.e Knockout.ObservableString();
Anyway the 2nd point is more about how to use these implementations in real world scenarios, as normally I would do something like:
function SomeClass() {
var self = this;
self.SomeObservable = ko.observable("default-value");
}
Now I was expecting to do something like this:
/// The Ref
interface ISomeClass {
SomeObservable: KnockoutObservableString;
}
class SomeClass implements ISomeClass {
// What goes here?
}
Now pretend for a minute that there is some logical reason to make my POJO (I guess it should be called a POTO now though) an interface then implement it, as normally I wouldn't bother putting an interface on anything which has 0 behaviour.
Now in the above example the interface would be fine as there is a KnockoutObservableString interface, however I couldn't find an implementation, so am I not meant to be using that interface or should I be making my own implementations?
I could do with someone to just point me in the direction and answer:
A) Why it wasn't written as a module?
B) How do you actually use the descriptors properly?
The descriptors are used to apply types to an existing javascript library, but they don't redefine the library interface or cause anything to change when compiling to javascript. I think this comes into play with both of your questions:
A) The knockout descriptor cannot be defined in a module because knockout defines ko as a global variable. Suppose ko had been defined in a Knockout module within the descriptor. Then the generated javascript that is generated by typescript would be something like SomeObservable = Knockout.ko.observable("default-value"), which is not valid.
B) For the most part, invoking knockout within typescript will look the same as javascript. So you could do something like this:
class SomeClass implements ISomeClass {
SomeObservable = ko.observable("default-value");
}
The descriptor file defines several overloads for ko.observable, and the one that takes a string argument returns a KnockoutObservableString. So the implementation and use of ko doesn't really change much... the only thing the descriptor really gives you is a little more type safety.
Right I think I may have a bit more of an idea about all this...
Now to answer the B) I think you are supposed to use them by including them which would be like:
declare var ko: KnockoutStatic
However if you look at the bottom of the knockout descriptor its already done for you, and then I think you are meant to use the interfaces for the interfaces you make, then the ko.xxx for your actual implementations, such as below:
/// <reference path="knockout.d.ts" />
interface IPerson
{
Forename: KnockoutObservableString;
Surname: KnockoutObservableString;
}
class Person implements IPerson
{
Forename = new ko.observable("");
Surname = new ko.observable("");
}
Although Rubymine 5 seems to think that the assignment to Forename and Surname is invalid, but I dont know why visual studio seems to think its ok.
So I hope someone else can verify im on the right track here.

IS OOP possible in Javascript?

I recently found out that Javascript function can have classes, so I was wondering if OOP is also possible through javascript. Is It? If yes, Could you please point out some tutorials or site, where I can start with?
OOP is definitely possible. While Javascript doesn't have "classes" like most OO languages do, what it does have is called "prototypes". Basically, objects are defined in terms of other objects rather than classes. (Objects can also emulate classes to some degree, for those who can't wrap their minds around prototypal inheritance.)
One could argue JS's OO capabilities exceed those of most languages, considering objects play an even more essential role than in languages with classes.
OOP is central to Javascript, but it's not classical OOP. Javascript uses prototypes, not classes.
Douglas Crockford is a Javascript genius, so his Prototypal Inheritance in Javascript is a nice starting point. A Google search for "Javascript OOP" likely will turn up some neat articles to peruse, as well — I like the article by Mike Koss.
Javascript is an intrinsically OOP language. Like others have said, it is classless, but you have a choice of how you want to create objects.
You can create objects that make use of different types of inheritance.
A pseudo-classical inheritance. Here you build constructor functions and use new to create classes. This will look most like the typical class based OOP.
Prototypal inheritance. - This is what many of the other answer referred to.
Functional inheritance. - In this mode you make use of closures, anonymous functions, and strategic returns to create truly private and protected variables.
There's a fair amount of cross over among these types. Suffice it to say that Javascript is a very flexible and powerful language for OOP.
I'm just learning about OOP in JS as well. Here is an example of functional inheritance I put together:
jsFiddle
// Object constructor
var parent = function (initial) {
var that, privateNumber, hiddenVar;
that = {};
// Public variables
that.share = initial - 32;
// Public methods
that.getNumber = function () {
return privateNumber;
};
// Private properties
privateNumber = initial;
hiddenVar = "haha can't get me";
return that;
};
// Second object constructor that inherits from parent
var child = function (initial) {
var that, privateName;
// Inherit from parent
that = parent(initial);
// Public methods
that.getName = function () {
return privateName;
};
// Private poroperties
privateName = "Ludwig the " + initial + "th";
return that;
};
// Create objects
var newPar1 = parent(42);
var newPar2 = parent(10);
var newChild1 = child(0);
var newChild2 = child(100);
// Output on the jsFiddle page refed above: http://jsfiddle.net/ghMA6/
http://msdn.microsoft.com/en-us/magazine/cc163419.aspx
http://www.dustindiaz.com/namespace-your-javascript/
http://vimeo.com/9998565
frameworks for oop js
http://jsclass.jcoglan.com/
http://www.prototypejs.org/
Pluralsight - JavaScript for C# Developers - Shawn Wildermuth - 2h 5m
JavaScript Basics
JavaScript Functions
Object-Oriented JavaScript
Practical Application
and
Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries - 356 pages -2008 -packed publishing
Yes. It is possible. I have ever using the Script# to build javascript application, It allow you writing C# code, and translate to JavaScript.
it is an good experience, especially for large project, it will force your thinking in the OOP way to order your code.
The tool can be found at: (it is open source but write by an Microsoft employee)
http://scriptsharp.com
If you are not familiar with C# you can also find the similar tool for writing javascript in Java.
And if you don't want to using those too, you can investigate how it convert the code to understand how it implement the OOP feature.
Here is an example of accomplishing an OO structure in javascript that is utilizing a library(not required, recommended)
//Create and define Global NameSpace Object
( function(GlobalObject, $, undefined)
{
GlobalObject.PublicMethod = function()
{
///<summary></summary>
}
GlobalObject.Functionality = {}
}) (GlobalObject = GlobalObject || {}, jQuery);
//New object for specific functionality
( function(Events, $, undefined)
{
//Member Variables
var Variable; // (Used for) , (type)
// Initialize
Events.Init = function()
{
///<summary></summary>
}
// public method
Events.PublicMethod = function(oParam)
{
///<summary></summary>
///<param type=""></param>
}
// protected method (typically define in global object, but can be made available from here)
GlobalObject.Functionality.ProtectedMethod = function()
{
///<summary></summary>
}
// internal method (typically define in global object, but can be made available from here)
GlobalObject.InternalMethod = function()
{
///<summary></summary>
}
// private method
var privateMethod = function()
{
///<summary></summary>
}
Events.PublicProperty = "Howdy Universe";
}) (GlobalObject.Functionality.Events = GlobalObject.Funcitonality.Events || {}, jQuery )
// Reusable "class" object
var oMultiInstanceClass = function()
{
// Memeber Variables again
var oMember = null; //
// Public method
this.Init = function(oParam)
{
oMember = oParam;
}
}
The strength to this is that it initializes the Global object automatically, allows you to maintain the integrity of your code, and organizes each piece of functionality into a specific grouping by your definition.
This structure is solid, presenting all of the basic syntactical things you would expect from OOP without the key words.
There are even some ingenious ways to set up interfaces as well. If you choose to go that far, a simple search will give you some good tutorials and tips.
Even setting up intellisense is possible with javascript and visual studio, and then defining each piece and referencing them makes writing javascript cleaner and more manageable.
Using these three methods as needed by your situation helps keep the global namespace clean, keep your code organized and maintains separation of concerns for each object.. if used correctly. Remember, Object Oriented Design is of no use if you don't utilize the logic behind using objects!

How do you structure your jQuery code?

Coming from mootools and JAVA, mootools class implementation is a real nice way to structure my code, plus I can have some nice features like extending, implementing and so on. Starting with jquery I found my self writing $.fn plugins that cant use code of other plugins. Plus it seems no good idea to use the plugin structure for complex stuff that hasn't much to do with DOM Elements. Is there a better way then $.fn? What do you recommend to structure my code using jquery.
This is a tough question to answer.
JavaScript's incredible flexibility's downside is that every programmer and his brother-in-law has a different way of doing things.
The downside of pulling in a library for doing "Class" based OOP in JavaScript (Prototype library, Moo, Joose, JS.Class, Base2, etc.) is that you immediately cut down on the number of fellow JavaScript programmers who can read your code.
Obviously, jQuery encourages you to think in terms of "collections." A collection is what you get back from a $() or jQuery() call. John Resig once considered adding a class system to jQuery, but finally decided against it. I think he's said that he's never needed a real "Class" system in JavaScript programming.
For all but the largest JS projects, I'd say forget about a Class system. Leverage JS's incredible object and array system (including literals). Namespace heavily (variables and methods alike).
I've had a lot of luck using arrays of objects for most situations I'd normally use Classes for.
An interesting extension of the jQuery collection concept is in Ariel Flesler's jQuery.Collection plugin here. It lets you treat "normal" data much as you would treat DOM data in jQuery.
I recently started using Underscore.js, which gives you a lot of functional tools to treat your data as collections.
What you generally need are mechanism for code extension and packaging.
For the former, I use the pseudo class-based default oo mechanism, sometimes with a helper function to make inheritance easier:
Function.prototype.derive = (function() {
function Dummy() {}
return function() {
Dummy.prototype = this.prototype;
return new Dummy;
};
})();
function Base() {}
function Sub() {}
Sub.prototype = Base.derive();
The latter can be achieved by namespacing via self-executing functions. It's even possible to fake import statements:
// create package:
var foo = new (function() {
// define package variables:
this.bar = 'baz';
this.spam = 'eggs';
// export package variables:
this.exports = (function(name, obj) {
var acc = [];
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
acc.push(prop + '=' + name + '.' + prop);
}
return 'var ' + acc.join(',') + ';';
})('foo', this);
});
// use package:
(function() {
// import package variables:
eval(foo.exports);
alert(spam);
})();
jQuery isn't really meant to be used for structuring your code. It's meant to be a tool that you use from your other code, not a way of life.
The rest of your code should be written whatever way you like. Just use jQuery when you want to do DOM manipulation, Ajax calls, cross-browser events, etc.
You may want to learn how to use the .prototype property to put some of your code into "classes", so that you can reuse the same code in different places, by just creating a new instantiation, basically.
You can also put code into objects so that you have a unique namespace, so it is easier to share related objects amongst different projects.
Basically you will be structuring your code as you do for straight javascript, but jQuery abstracts out some of the common functionality so you don't have to worry about browser issues, but it is just a helper, it really doesn't provide a framework as much as just making some concepts simpler. For example, rather than using onclick I tend to use .bind('click', ...) but that is if I want to have the potential of more than one event hander on an element.

Language with similar object use to Javascript/JSON

I've been doing a project at work recently focused on an almost entirely client-driven web site. Obviously Javascript is used heavily, and I've been using jQuery on top of it which has turned out to be an absolute pleasure to work with.
One of the things that has surprised me in this is how much I like the JSON object syntax and it's use within javascript (highlighted by jQuery, which uses it everywhere). for those that aren't familiar with it, consider this brief example:
function add(params) {
params.result(params.a, params.b);
}
add({
a: 1,
b: 2,
result: function(value) {
alert(value);
}
});
Of course, this example is extremely contrived but it illustrates the basic usage. The JSON describes an object on the fly, passed in this case as a parameter to the function, and even defines a function within it for use as a callback. I personally find this methodology very easy to use, understand, and produce APIs with (though I know there are those that would disagree with me.)
So my question is, is this type of syntax unique to javascript? I know that many languages have JSON parsers (and have used several) but they don't allow for this sort of inlined declaration. And granted, much of what you can do with this syntax can be duplicated via named parameters in various languages and lambda expressions or function pointers (Python jumps to mind), but I still don't find that quite as elegant.
Just curious, thanks for any replies!
The canonical example is Lisp: in Lisp, the language isn't even defined in terms of text, it is defined in terms of data structures. There really is not difference between code and data: code is just a list whose first element is interpreted as an operation and the rest as operands.
Writing a program is just writing lists.
Lua uses "tables" which are pretty much identical to javascript objects.
Syntax of JSON is very similar to Perl definition of complex structures. And your example would be:
#!/usr/bin/perl
use strict;
use warnings;
use signatures;
sub add($hash) {
$hash->{result}($hash->{a}, $hash->{b});
}
add({
a=> 1,
b=> 2,
result=> sub ($val) {
print "$val\n";
}
});
C# 3.0 has something similar in that you can both instantiate an object using a default constructor and assign properties in the same statement. It's really just a bit of syntactic sugar, but it really make it much easier than declaring multiple constructors just to handle various combinations of parameter settings. It looks like:
var myObject = new MyClass { Property1 = "value", NumericProperty = 1 };
There are also anonymous types in C# 3.0 which have a similar syntax; these are frequently used with LINQ
var query = dataContext.Entity
.Where( e => e.Kind = 1 )
.Select( e => new { e.Name, e.Kind } );
This results in an IEnumerable of a new anonymous type with properties "Name" and "Kind" which, in turn, have the same types as the corresponding entity properties.
Rubists would do:
def add(params) {
params.result(params.a, params.b)
}
add({:a=> 1, :b=> 2}) do |value|
alert(value)
end
The passing of an optional block is kind of a weird idiom in ruby. Or to be more true to your example.
def add(params) {
params.result(params.a, params.b)
}
add({
:a=> 1,
:b=> 2,
:result=> proc do |value|
alert(value)
end
})
But the concept of the inline function originates from lambda calculus and LISP.

Categories