Why this...
class Person
name: "initial name"
constructor: (#name) ->
class User extends Person
password: "initial password"
f = new User "Felds"
console.log f
console.log "my name is '#{f.name}' and my password is '#{f.password}'"
b = new User "Bob"
b.password = "bob's password"
console.log b
... when run through coffee -p test.coffee | node outputs this?
{ name: 'Felds' }
my name is 'Felds' and my password is 'initial password'
{ name: 'Bob', password: 'bob\'s password' }
Why doesn't the password property show on console.log f ? Where is it stored and how is it retrieved?
The 'initial password' value is stored in Person.prototype.password. Person.prototype is an object with all the common attributes shared between Person instances. When you access aPersonInstance.password, the password property is first looked up in the aPersonInstance object; if it's not found there it will be looked up in its prototype, and then in its prototype's prototype and so on.
console.log f will not show f's prototype properties, only the properties stored in f themselves (also known as f's own properties). When you assign Bob's password with b.password = 'bob\'s password' you're creating a new password property in b itself, which will now be the value of accessing b.password, even though b's prototype still has the 'initial password' value. I hope that made some sense =P
By storing 'initial password' in the prototype you're sharing that value between all Person instances as a kind of default value. This is perfectly fine to do with strings or other primitive (immutable) types; but you have to take special care if you're going to do it with arrays or other mutable objects, because the same object will be shared between all the class' instances, and if one of them modifies it, e.g. #someArray.push 5, all the other ones are going to see it. In those cases, it's usually preferable to initialize the attribute in the class constructor, like #someArray = [], to guarantee that each instance will have a different array/object attribute.
I want to give u a simple&quick answer but not exactly right in Javascript:
The variable password which you defined in class User is User.prototype.password, the variable just like class variable in OO language.
It is not f's instance variable, so when you console.log f, u cant see password.
but if you retrieve f.password, then u will still get the value 'initial password'. when a instance cant find a variable in itself, it will continue finding it in its class, that is User.
b.password is a instance variable in b, so console can log it out.
Related
I have two Visualforce pages, and for several reasons I've decided it is best to pass a datetime value between them as a string. However, after my implementation my date always appear to be null even though my code seems to compile.
I have researched quite a few formatting topics but unfortunately each variation of the format() on date time seems to not produce different results.
The controller on page 1 declares two public variables
public datetime qcdate;
public String fdt;
qcdate is generated from a SOQL query.
wo = [SELECT id, WorkOrderNumber, Quality_Control_Timestamp__c FROM WorkOrder WHERE id=:woid];
qcdate = wo.Quality_Control_Timestamp__c;
fdt is then generated from a method
fdt = getMyFormattedDate(qcdate);
which looks like this
public String getMyFormattedDate(datetime dt){
return dt.format(); }
fdt is then passed in the URL to my next VF page.
String url = '/apex/workordermaintenanceinvoice?tenlan='+tenlan +'&woid=' + woid + '&invnum=' + invnum + '&addr1=' + addr1 + 'fdt=' + fdt;
PageReference pr = new PageReference(url);
I expected when calling {!fdt} on my next page to get a proper string. But I do not.
UPDATE:
Sorry I guess I should not have assumed that it was taken for granted that the passed variable was called correctly. Once the variable is passed the following happens:
The new page controller creates the variable:
public String fdt
The variable is captured with a getparameters().
fdt = apexpages.currentPage().getparameters().get('fdt');
The getfdt() method is created
public String getfdt(){
return fdt;
}
Which is then called on the VF page
{!fdt}
This all of course still yields a 'blank' date which is the mystery I'm still trying to solve.
You passed it via URL, cool. But... so what? Page params don't get magically parsed into class variables on the target page. Like if you have a record-specific page and you know in the url there's /apex/SomePage?id=001.... - that doesn't automatically mean your VF page will have anything in {!id} or that your apex controller (if there's any) will have id class variable. The only "magic" thing you get in apex is the standard controller and hopefully it'll have something in sc.getId() but that's it.
In fact it'd be very stupid and dangerous. Imagine code like Integer integer = 5, that'd be fun to debug, in next line you type "integer" and what would that be, the type or variable? Having a variable named "id" would be bad idea too.
If you want to access the fdt URL param in target page in pure Visualforce, something like {!$CurrentPage.parameters.fdt} should work OK. If you need it in Apex - you'll have to parse it out of the URL. Similar thing, ApexPages.currentPage() and then call getParameters() on it.
(Similarly it's cleaner to set parameters that way too, not hand-crafting the URL and "&" signs manually. If you do it manual you theoretically should escape special characters... Let apex do it for you.
I am going back and working through old coursework from my intro to comp sci class, and on one of the labs I'm supposed to use the flickrapi module to scrape flickr for a set of pictures to use for the rest of the lab. The project was assigned with some code to scrape flickr that I know should work, but whenever I run the code it throws a TypeError. The function that is returning an error is:
def getphotos(apicode, query, num_images):
''' Return a list of URLs that have a tag that
matches the query code. '''
# Form the object that will interact with the Flickr website
flickr = flickrapi.FlickrAPI(apicode, format='etree')
# Get each matching photo and store in a list, stopping when we
# reach the target number of images
photos = []
for photo in flickr.walk(tags = query, tag_mode = 'all', safe_search = '0', sort = 'interestingness-desc'):
url = "http://farm" + photo.get('farm') + ".staticflickr.com/" + \
photo.get('server') + "/" + photo.get('id') + "_" + \
photo.get('secret') + ".jpg"
print url
photos.append(url)
if len(photos) >= num_images:
break
return photos
The line that throws the error is flickr = flickrapi.FlickrAPI(apicode, format='etree') where apicode represents an apicode key given to me by flickr and I'm not quite sure what the format ='etree' does. When I go look at the flickrapi module and go into core.py, I get to the FlickrAPI class. The part of the class that seems to be of interest is given as:
class FlickrAPI(object):
"""Encapsulates Flickr functionality.
Example usage::
flickr = flickrapi.FlickrAPI(api_key)
photos = flickr.photos_search(user_id='73509078#N00', per_page='10')
sets = flickr.photosets_getList(user_id='73509078#N00')
"""
REST_URL = 'https://api.flickr.com/services/rest/'
UPLOAD_URL = 'https://up.flickr.com/services/upload/'
REPLACE_URL = 'https://up.flickr.com/services/replace/'
def __init__(self, api_key, secret, username=None,
token=None, format='etree', store_token=True,
cache=False):
...(followed by logic statements involving the inputs for __init__ and class methods)
When flickr gives me an apicode key, it also gives me a secret key which I have stored in a .txt file in the same directory as the program I'm working on.
Now obviously the call on the FlickrAPI class is being passed 3 arguments, 2 of which are the apicode key and the format ='etree', but I'm a little bit unsure as to what the third one is. Is the class somehow calling on the secret key through flickr, or is it one of the other inputs for init? How do I got about fixing the type error that the code is giving me?
The three required arguments are self, api_key and secret (arguments that have no default value), the example given in the docstring of the FlickrAPI does not work.
Here, the first argument, self, is implicit (it's the instance of the FlickrAPI being constructed itself), you are giving the second argument, api_key, with apicode, but the third required argument, secret, is missing. format is the third argument you give, but it doesn't count in the three required arguments, as it has a default value.
The problem is that you don't pass anything for secret.
Take a look at this example
class Test():
def __init__(self, one, two, three=3):
print one, two, three
Test(1, three=3)
Test.__init__ takes four arguments, of which one (three) has a default value, so it needs at least self, one and two passed to it. self is passed automatically because it is a class method, so that's the first. Then you pass something for one and something for three. You do pass three arguments, which is the minimum, but you pass nothing for two, which doesn't have any default value. That's where the error comes from. You could call Test(1, 2) which has the same number of arguments because then all arguments without a default value are provided.
In your code, you are passing an argument for api_key and an argument for format, but nothing for secret, which doesn't have a default value.
I want to add two custom fields for newsletter subscriber at which date customer subscribed and its ip address:
1) I had added two columns in ‘newsletter_subscriber’ table.
How this can be achieved?
In the file app/code/core/Mage/Newsletter/Model/Subscriber.php
I found the the functions like:
$this->setSubscriberEmail($email);
$this->setStoreId(Mage::app()->getStore()->getId());
$this->setCustomerId(0);
But i did not found its code.
I think I also save data like that but how it will be possible ? where I have to define and declare code for the function like $this->seSubscriptionDate();
And how to display in Admin panel under Newsletter->Newsletter Subscriber ?
I had not find the solution or help from any person.
I bang my head and find the solution its very simple hope in future may some one’s time save by this post:
1) Add columns in the table “newsletter_subscriber” say in my case “subscription_date” and “sub_ip_address”
2) Add following two lines in the file # two places
app\code\core\Mage\Newsletter\Model\Subscriber.php
**$this->setSubscriptionDate(date("d-m-Y"));
**$this->setSubIpAddress($_SERVER['REMOTE_ADDR']);
One place: in the function: public function subscribe($email)
Before: $this->save();
Second place: in the function: public function subscribeCustomer($customer)
Before: $this->save();
Now data will be added in the table
Now to show in admin panel
1) Open the file app\code\core\Mage\Adminhtml\Block\Newsletter\Subscriber\Grid.php
Just add two required columns in it like
$this->addColumn('subscription_date', array(
'header' => Mage::helper('newsletter')->__('Subscription Date'),
'index' => 'subscription_date',
'default' => '----'
));
$this->addColumn('sub_ip_address', array(
'header' => Mage::helper('newsletter')->__('IP Address'),
'index' => 'sub_ip_address',
'default' => '----'
));
Now finish.
** This is the point where I spent my time and at the end I added this function on hit and trieal basis but it works.
Someone from Core magento team plz explain why this {setSubscriptionDate()}function work ? I had not declared anybody of this function.
It seems it shows intellisense to detect table field?
I also had the similar problem. However, in my case I am supposed to add a "country" and "gender" field in the newsletter form. So, on digging into the core for hours I figured this out. Below is the explaination:
In the app/design/frontend//default/template/newsletter/subscribe.phtml,
the form has getFormActionUrl() ?> in its action field. This referes to app/code/core/Mage/Newsletter/Block/Subscribe.php
The $this object used in the subscirbe.phtml file referes to this class (i.e. Mage_Newsletter_Block_Subscribe) and thus $this->getFormActionUrl() in the subscribe.phtml file refers to the function getFormActionUrl() of this class.
Now, this getFormActionUrl() is returning a method $this->getUrl('newsletter/subscriber/new', array('_secure' => true)) which belongs to its parent Mage_Core_Block_Template (I mean the method getURL()). This part is not improtant to us.
See the parameter passed to the getURL() function which is newsletter/subscriber/new
The first part "newsletter" is the module name (app/code/code/Mage/newsletter), the second part "subscriber" is the controller name (app/code/code/Mage/newsletter/controllers/SubscriberController) and the third part "new" is the method newAction in the controller SubscriberController.
Controller names are suffixed with Controller and function names are suffixed by Action. (Thanks to Phalcon framework to help understand this)
Now in the newAction() method you can see that by default, only the email is being posted
as
$email = (string) $this->getRequest()->getPost('email');
What I did was, I cloned the subscribe.phtml template with a name custom-newsletter.phtml and add two fields with name "country" and "gender". Then added the following lines in the newAction():
$country = (string) $this->getRequest()->getPost('country');
$gender = (string) $this->getRequest()->getPost('gender');
Now at line number 67 of the SubscriberController (inside the newAction() method) there is a code :
$status = Mage::getModel('newsletter/subscriber')->subscribe($email);
This line is calling the subscribe method of app/code/code/Mage/newsletter/Model/Subscriber.php and is passing the $email that is posted from newsletter form into it. I modified the line as:
$status = Mage::getModel('newsletter/subscriber')->subscribe($email,$country,$gender);
Now, I have to edit the app/code/code/Mage/newsletter/Model/Subscriber.php
When we talk about Models, we are talking about the database table the Model refers to. The model name is Subscriber and it belongs to module Newsletter so, the database table that this model affects is newsletter_subscriber
From this part on #Hassan Ali Sshahzad's question will be answered.
I added two new columns there with the name: subscriber_country and subscriber_gender.
Now, Magento' system automatically makes available a getter and a setter function to these columns with the following name:
function getSubscriberCountry(){}
function setSubscriberCountry($country_name){}
So, all I had to do in the model was:
Edit the method subscribe($email) to subscribe($email,$country,$gender)
add the following code in the subscribe($email,$country,$gender) function right before the try statement as follows:
$this->setSubscriberCountry($country);
$this->setSubscriberGender($gender);
try{
$this->save()
Hassan's method played a key role in my understanding of the MVC of Magento so its a return from my side.
I am using RoR 3.1 + Postgres on MacOSX
In my create function I have this:
def create
#power_plant_substrate = PowerPlantSubstrate.new(params[:power_plant_substrate]) <= 1
#trade = params[:power_plant_substrate][:trade]
respond_to do |format|
if #power_plant_substrate.save
...
end
(1) should instantiate a new object with params[:power_plant_substrate]
THE PROBLEM:
Right after the creation of my new object #power_plant_substrate some of the attribute are available.
if I check params[:power_plant_substrate] value (trace to console) I can verify that all fields were passed correctly:
{"power_plant_id"=>"161", "substrate_id"=>"213", "quantity"=>"1", "periodicity"=>"yearly", "trade"=>"wanted", "price_per_unit"=>"0.00", "total_price"=>"0.00", "currency"=>"USD", "address"=>", Reserved", "transport"=>"pickup_only", "description"=>"afewrqe", "latitude"=>"", "longitude"=>""}
However I checked my object right after saving (#power_plant_substrate.save). "trade" attribute is not assigned anymore.
I tried accessing the same attributes in the model in a method that I call after_create, and same problem.
However, the record is available with all fields correctly assigned in the database.
WHY #power_plant_substrate object doesn't appear "fully" assigned after saving?
Hope you can help.
My guess is that there is a list of attr_accessible in PowerPlantSubstrate model. check if currency and trade are added in that list. If not, then add those.
attr_accessible :currency, :trade, . . .
Making a few attributes alone as attr_accessible will make it impossible to mass assign other variables. That is why individual assignment worked
If there is not list, try adding
attr_accessible nil
and see if that works
I have a class student with 2 variables one string name and other integer roll.
using
this.frame.Navigate(typeof(Page1),s1); //s1 is an object of class student
I am trying to pass an object to page1
But I am not able to access any of the variables of s1 on page1.
in the NavigatedTo method of Page1 I have written:
student x= e.Parameter as student;
student n= new student();
n.name=x.name;
in whichever I try to access object x variables it throws a "NullReferenceException unhandled by the user code"
"object reference not set to an instance of an object"
not able to find a solution for this.
Have you tried using student x = e.ExtraData as student? Here is some relevant Msdn doco.