How to get YUI object on page - object

I'm using the YUI2 framework.
I want to be able to get a reference to an object that was created on the page. I don't want to change the existing JS code to store a global handle to it when it is created, if possible.
The page has something like this on it:
<script type="text/javascript">//<![CDATA[
new FirstRate.Reporter("report1").setOptions(
{
inData: "testfunc"
}));
//]]></script>
I don't see any methods in YAHOO.util.Dom specific to finding objects.
How can I get an object reference to FirstRate.Reporter? Is there anything to ennumerate the objects on the page?
Thanks

YUI contains lots of methods for finding objects in the webpage DOM. YAHOO.util.DOM contains methods:
HTMLElement | Array get ( el )
Array getElementsBy ( method , tag , root , apply , o , overrides )
HTMLElement getElementBy ( method , tag , root )
Array getElementsByClassName ( className , tag , root , apply , o , overrides )
and many more. These retrieve objects from the DOM. To find an object in the page with YUI2, you would typically use some combination of the tag type, the class name or the id to query the page using YUI methods to find the object you want. It's easiest to find a specific object in the page if you give it a unique id value and then you can just using YAHOO.util.DOM.get("myObject") to retrieve it (where "myObject" is the id of the HTML element).
If you want to get regular javascript objects, then you have to store references to them yourself in your own javascript variables. YUI doesn't do that for you except when using some UI widgets (which also have DOM elements).
If you want to keep track of the result of this:
new FirstRate.Reporter("report1").setOptions(
{
inData: "testfunc"
})
Then, you have to assign it to a variable or to a property of an object whose scope allows it to last long enough for you to use it.
var theReporter = new FirstRate.Reporter("report1").setOptions(
{
inData: "testfunc"
})
or
myObject.reporter = new FirstRate.Reporter("report1").setOptions(
{
inData: "testfunc"
})
where myObject is some other object you've created and are storing.

JavaScript objects aren't part of DOM. DOM is the Document Object Model, it's about objects in HTML document like divs, forms, inputs etc, the kind of objects Browser displays.
There is no "global enumeration" of objects in JavaScript. There are global variables.
I don't want to change the existing JS code to store a global handle to it
So you don't want to use global variable. But why?
This is the only way to do it, and it's also very simple:
var myGlobalVar = new FirstRate.Reporter("report1").setOptions({inData: "testfunc"}));
Here you'll store reference ("handle" as you say) to your object in global var myGlobalVar, which you can later access in another part of your JavaScript code.

Related

How to render only one document in jade view?

I need to display only one document from my CouchDB, but if I don't create for-each loop, I can't define variable employer
.row
.col-xs-12.col-sm-8
.row.list-group
each employer in the employers
.col-xs-12.list-group-item
h4
p #{employer.value.name}, #{employer.value.location} #{employer.value.type}, #{employeer.value.position}
small
.col-xs-12.col-sm-4
p.lead= sidebar
When I try to display only one document without the loop, I am receiving an error: Cannot read property 'value' of undefined
If employeers is an array, you should be able to do something like:
employeers[0].value.name
If you want to keep using "employer" you can also replace your each loop with:
- var employer = employeers[0];

Can't modify/remove a field from an ActivityNode using sbt

I created an ActivityNode (an Entry) and I can add custom fields with the
setFields(List<Field> newListField)
fonction.
BUT
I am unable to modify these fields. (In this case I try to modify the value of the field named LIBENTITE)
FieldList list = myEntry.getTextFields();
List<Field> updatedList = new ArrayList<Field>();
//I add each old field in the new list, but I modify the field LIBENTITE
for(Field myField : list){
if(myField.getName().equals("LIBENTITE")){
((TextField)myField).setTextSummary("New value");
}
updatedList.add(myField);
}
myEntry.setFields(updatedList);
activityService.updateActivityNode(myEntry);
This code should replace the old list of fields with the new one, but I can't see any change in the custom field LIBENTITE of myEntry in IBM connections.
So I tried to create a new list of fields, not modifying my field but adding a new one :
for(Field myField:list){
if(!myField.getName().equals("LIBENTITE")){
updatedList.add(myField);
}
}
Field newTextField = new TextField("New Value");
newTextField .setFieldName("LIBENTITE");
updatedList.add(newTextField );
And this code is just adding the new field in myEntry. What I see is that the other custom fields did not change and I have now two custom fields named LIBENTITE, one with the old value and the second with the new value, in myEntry.
So I though that maybe if I clear the old list of Fields, and then I add the new one, it would work.
I tried the two fonctions
myEntry.clearFieldsMap();
and
myEntry.remove("LIBENTITE");
but none of them seems to work, I still can't remove a custom field from myEntry using SBT.
Any suggestions ?
I have two suggestions, as I had (or have) similar problems:
If you want to update an existing text field in an activity node, you have to call node.setField(fld) to update the field in the node object.
Code snippet from my working application, where I'm updating a text field containing a (computed) start time:
ActivityNode node = activityService.getActivityNode(id);
node.setTitle(formatTitle()); // add/update start and end time in title
boolean startFound = false;
// ...
FieldList textfields =node.getTextFields();
Iterator<Field> iterFields = textfields.iterator();
while (iterFields.hasNext()) {
TextField fld = (TextField) iterFields.next();
if (fld.getName().equals(Constants.FIELDNAME_STARTTIME)) {
fld.setTextSummary(this.getStartTimeString()); // NOTE: .setFieldValue does *not* work
node.setField(fld); // write updated field back. This seems to be the only way updating fields works
startFound=true;
}
}
If there is no field with that name, I create a new one (that's the reason I'm using the startFound boolean variable).
I think that the node.setField(fld) should do the trick. If not, there might be a way to sidestep the problem:
You have access to the underlying DOM object which was parsed in. You can use this to tweak the DOM object, which finally will be written back to Connections.
I had to use this as there seems to be another nasty bug in the SBT SDK: If you read in a text field which has no value, and write it back, an error will be thrown. Looks like the DOM object misses some required nodes, so you have to create them yourself to avoid the error.
Some code to demonstrate this:
// ....
} else if (null == fld.getTextSummary()) { // a text field without any contents. Which is BAD!
// there is a bug in the SBT API: if we read a field which has no value
// and try to write the node back (even without touching the field) a NullPointerException
// will be thrown. It seems that there is no value node set for the field. We
// can't set a value with fld.setTextSummary(), the error will still be thrown.
// therefore we have to remove the field, and - optionally - we set a defined "empty" value
// to avoid the problem.
// node.remove(fld.getName()); // remove the field -- this does *not* work! At least not for empty fields
// so we have to do it the hard way: we delete the node of the field in the cached dom structure
String fieldName = fld.getName();
DeferredElementNSImpl fldData = (DeferredElementNSImpl) fld.getDataHandler().getData();
fldData.getParentNode().removeChild(fldData); // remove the field from the cached dom structure, therefore delete it
// and create it again, but with a substitute value
Field newEmptyField = new TextField (Constants.FIELD_TEXTFIELD_EMPTY_VALUE); // create a field with a placeholder value
newEmptyField.setFieldName(fieldName);
node.setField(newEmptyField);
}
Hope that helps.
Just so that post does not stay unanswered I write the answer that was in a comment of the initial question :
"currently, there is no solution to this issue, the TextFields are read-only map. we have the issue recorded on github.com/OpenNTF/SocialSDK/issues/1657"

Passing data in a pop/back event to a previous view model

I have a structure like so :
SessionsView -> CreateSessionView
with view models like so :
SessionsViewModel - List of Session objects
CreateSessionViewModel - Single Session Object
The user fills in a form in create session, populates the Session object on the view model, hits done and I call : NavigationController.PopViewControllerAnimated(true) to take them back to the list of sessions.
Is there a way of passing my newly created session object back to the previous views Viewmodel and adding it to its list of session objects? I know how to pass params in a ShowViewModel<TYPE>(PARAM) command, but not sure how to do it whilst navigating back.
Update 1 :
I found 'a' way to do it.. doesn't feel too nice though :
var sessionsView = (SessionsView)NavigationController.ViewControllers.FirstOrDefault(vc => vc is SessionsView);
var sessionsViewModel = (SessionsViewModel)sessionsView.ViewModel;
sessionsViewModel.Sessions.Add(vModel.Session);
NavigationController.PopViewControllerAnimated(true);
Just make use of the return parameter of PopViewControllerAnimated(bool animated).
NavigationController.PopViewControllerAnimated(true);
ViewControllerClass viewController = (ViewControllerClass)NavigationController.TopViewController;
viewController.StoreSessionObject(session); <-- you need to create this method

How to assign a value to an Orchard ContentPickerField from code?

I am working on an Orchard site that needs to be able to use some customized forms to create new content items.
To handle this I'm using a controller to display a form and then trying to create the new content items on post back by populating the dynamic items and then sending them through the ContentManagerService's Create() function.
This is working ok until I got to the content picker field I have as part of my content item.
In my project I have a content type of Question Record that has a SubmittedBy field that is a Content Picker Field.
Here is what I can see in the immediate window while processing the post back:
> dynamic q = _questionService.NewQuestion("Why doesn't this work?");
{Custom.Website.Models.Question}
base {Orchard.ContentManagement.ContentPart}: {Custom.Website.Models.Question}
IsNew: true
OriginalQuestion: "Why doesn't this work?"
Summary: null
> q.QuestionRecord
{Orchard.ContentManagement.ContentPart}
base {System.Dynamic.DynamicObject}: {Orchard.ContentManagement.ContentPart}
ContentItem: {Orchard.ContentManagement.ContentItem}
Fields: Count = 5
Id: 0
PartDefinition: {Orchard.ContentManagement.MetaData.Models.ContentPartDefinition}
Settings: Count = 0
TypeDefinition: {Orchard.ContentManagement.MetaData.Models.ContentTypeDefinition}
TypePartDefinition: {Orchard.ContentManagement.MetaData.Models.ContentTypePartDefinition}
Zones: {Orchard.UI.ZoneCollection}
> q.QuestionRecord.SubmittedBy
{Orchard.ContentPicker.Fields.ContentPickerField}
base {Orchard.ContentManagement.ContentField}: {Orchard.ContentPicker.Fields.ContentPickerField}
ContentItems: null
Ids: {int[0]}
The ContentItems property is read-only and the Ids when assigning a new int[] to the Ids array I get a System.ObjectDisposedException with the message: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
Are there any workarounds to get this value set in code or do I need to create my own property to store the related content item ids? It would be very helpful to have the admin interface of the ContentPickerField also available.
Thanks.
If you have a reference to the ContentPickerField, you can assign it a value using the Ids property.
In example (assuming your content type has a part called Question which has a field called SubmittedBy):
var submittedByField = ((dynamic)q.ContentItem).Question.SubmittedBy;
sbmittedByField.Ids = new[] { submittedById };
As Bertrand mentioned, the format to access a content field is: contentItem.PartName.FieldName.
If you attached a field to a type directly via the admin, the part name has the same name as the type name, hence contentItem.TypeName.FieldName (where TypeName is actually the name of the implicitly created part).

What is the purpose of the SvgElement.tag(String tag) constructor?

There is no documentation in the API doc for the constructors. I would like to understand the purpose/use cases for SvgElement.tag() .
The SvgElement.tag(String tag) constructor creates a new SvgElement for a corresponding tag value.
For example:
var foo = new SvgElement.tag('view');
print(foo is ViewElement); // prints 'true'
would create a new SvgElement specified by the <view> tag.
This means that the above code is the same as:
var bar = new ViewElement();
print(bar is ViewElement); // prints 'true'
See also the tag constructor from the superclass Element.
Use cases for this constructor are places where you get the value of the tag from text and want to generate a new element of that tag value.
You might get the tag from parsing the DOM, or maybe from a different API. The tag constructor is a way to write DOM code in a "Darty" way (with objects and classes) while being able to work with DOM elements via text.
In many cases, it is preferable to create this Element object instead of say, using innerHtml to set the DOM inside of another Element.
Compare:
var someTagName = 'view';
var someDomNode = query('#id');
// BAD
someDomNode.innerHtml = '<$someTagName> ... </$someTagName>';
// GOOD
var myElement = new SvgElement.tag(someTagName);
someDomNode.append(myElement);

Resources