as3 why is my public var changing? - actionscript-3

I have a var called "currentMystery" I have reduced the issue down to these two functions
I believe. Anyway, the first time through it works and traces a var from an Array... but the second time through something is changing it to [Event type="soundComplete" bubbles=false cancelable=false eventPhase=2]
What in the code is changing this or what am I doing wrong?
Thanks so much!
Any ideas on how to keep it as the same var as it assigned here:
currentMystery = "" + Mystries[4] + "";
...
public static var Mystries:Array = new Array("null","Joyful","Luminous","Sorrowful","Glorious");
public function checkDecade(e:Event = null)
{
if (decadeCount < 6)
{
Announce = true;
currentMystery = "" + Mystries[4] + "";
prayDecade(currentMystery);
}
}
public function prayDecade(currentMystery:String)
{
//// MY ISSUE IS WITH currentMystery. First time through
//// it works but the second through it is changing to
//// something like [Event type="soundComplete" bubbles=false etc...
trace("Pray Decade called: " +currentMystery);
if (Announce)
{
/// Sets PAUSE before Announc || Add features later to all prayers
setTimeout(function()
{
MainDoc.cPrayer.text = currentMystery;
trace("Called Announce"+decadeCount);
trace("Called Announce: Mystery: " + currentMystery+" Current Decade: " +decadeCount);
theAnnounce = new Sound();
theAnnounce.load(new URLRequest("audio/Rosary/Announce/"+currentMystery+"/"+decadeCount+".mp3"));
Praying = theAnnounce.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
Announce = false;
}, 2000);
}
else
{
if (prayerCount==0)
{
trace("Our Father " + decadeCount);
//trace(love);
Begin = true;
/// Sets PAUSE before Our Father || Add features later to all prayers
setTimeout(function()
{
Begin = true;
ourFather();
}, 2000);
}
if (prayerCount >0 && prayerCount<11)
{
trace("Hail Mary " + prayerCount);
Begin = true;
hailMary();
}
if (prayerCount==11)
{
trace("Glory Be... " + prayerCount);
Begin = true;
gloryBe();
}
if (prayerCount==12)
{
trace("Oh My Jesus... " + prayerCount);
Begin = true;
ohMyJesus();
}
function ourFather(e:Event = null)
{
if (Begin)
{
Praying = OFB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, ourFather );
}
else
{
Praying = OFE.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
prayerCount++;
}
Begin = false;
}
function hailMary(e:Event = null)
{
if (Begin)
{
Praying = HMB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, hailMary );
}
else
{
Praying = HME.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
prayerCount++;
}
Begin = false;
}
function gloryBe(e:Event = null)
{
if (Begin)
{
Praying = GBB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, gloryBe );
}
else
{
Praying = GBE.play();
Praying.addEventListener(Event.SOUND_COMPLETE, checkDecade );
prayerCount++;
}
Begin = false;
}
function ohMyJesus(e:Event = null)
{
Praying = OMJ.play();
Praying.addEventListener(Event.SOUND_COMPLETE, checkDecade );
prayerCount = 0;
decadeCount++;
}
}//End if Else
}

You're using the prayDecade method as a handler for the sound complete event as well as calling it directly in your code. When it is invoked as an event handler, the parameter it receives is an event object which is being cast to a string and overwriting your public variable within the local (prayDecade function) scope.
I think if you update the function as follows you'll get the results you expect (assuming currentMystery is a public variable in the class scope:
public function prayDecade(e:Event)
{
trace("Pray Decade called: " + currentMystery);
// ....
}
And when you invoke the method directly, don't pass the variable:
// Assuming currentDecade is in scope in the prayDecade method
prayDecade(/*currentMystery*/);

What in the code is changing this or what am I doing wrong?
Event handler for the 'SoundChannel' is wrong.
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
In the prayDecade as an argument will be passed event object (Event.SOUND_COMPLETE), not a string as you are waiting for. So [Event type="soundComplete" bubbles=false cancelable=false eventPhase=2] is a String representation of event.

Related

chrome cast on chrome not sending message

if (!chrome.cast || !chrome.cast.isAvailable) {
setTimeout(initializeCastApi, 1000);
}
function initializeCastApi() {
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
sessionListener,
receiverListener);
chrome.cast.initialize(apiConfig, onInitSuccess, onError);
};
function sessionListener(e) {
//this function doenot runs firsttime
appendMessage('New session ID:' + e.sessionId);
session = e;
session.addUpdateListener(sessionUpdateListener);
session.addMessageListener(namespace, receiverMessage);
console.log(receiverMessage);
}
sessionListener() function doenot gets called first time.when session get updaed it gets called.Why is it so?

Parse URL (ActionScript 3.0)

I would like to know how would one parse an URL.
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
I need to get "this_is_what_i_want/even_if_it_has_slashes"
How should I do this?
Thanks!
Try this :
var u:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes',
a:Array = u.split('/'),
s:String = ''
for(var i=0; i<a.length; i++){
if(i > 3){
s += '/'+a[i]
}
}
trace(s) // gives : /morethings/this_is_what_i_want/even_if_it_has_slashes
Another approach would be using Regex like this:
.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)
(Breakdown of the components.)
This looks for a pattern where it skips whatever comes before the domain name (doesn't matter if the protocol is specified or not), skips the domain name + TLD, skips any port number, and skips the first two sub path elements. It then selects whatever comes after it but skips any query strings.
Example: http://regexr.com/39r69
In your code, you could use it like this:
var url:String = "protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes";
var urlExp:RegExp = /.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)/g;
var urlPart:Array = urlExp.exec(url);
if (urlPart.length > 1) {
trace(urlPart[1]);
// Prints "this_is_what_i_want/even_if_it_has_slashes"
} else {
// No matching part of the url found
}
As you can see on the regexr link above, this captures the part "this_is_what_i_want/even_if_it_has_slashes" for all of these variations of the url:
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html?hello=world
mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://subdomain.mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes
Edit: Fixed typo in regexp string
Simple way,
var file:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes';
var splitted:Array = file.split('/');
var str1:String = splitted.splice(3).join('/'); //returns 'something/morethings/this_is_what_i_want/even_if_it_has_slashes'
var str1:String = splitted.splice(5).join('/'); //returns 'this_is_what_i_want/even_if_it_has_slashes'
If you want to be a little more flexible in the feature (e.g. you need the domain), you can use my Url class.
Class for URL parsing
package
{
import flash.net.URLVariables;
public class Url
{
protected var protocol:String = "";
protected var domain:String = "";
protected var port:int = 0;
protected var path:String = "";
protected var parameters:URLVariables;
protected var bookmark:String = "";
public function Url(url:String)
{
this.init(url);
}
protected function splitSingle(value:String, c:String):Object
{
var temp:Object = {first: value, second: ""};
var pos:int = value.indexOf(c);
if (pos > 0)
{
temp.first = value.substring(0, pos);
temp.second = value.substring(pos + 1);
}
return temp;
}
protected function rtrim(value:String, c:String):String
{
while (value.substr(-1, 1) == c)
{
value = value.substr(0, -1);
}
return value;
}
protected function init(url:String):void
{
var o:Object;
var urlExp:RegExp = /([a-z]+):\/\/(.+)/
var urlPart:Array = urlExp.exec(url);
var temp:Array;
var rest:String;
if (urlPart.length <= 1)
{
throw new Error("invalid url");
}
this.protocol = urlPart[1];
rest = urlPart[2];
o = this.splitSingle(rest, "#");
this.bookmark = o.second;
rest = o.first;
o = this.splitSingle(rest, "?");
o.second = this.rtrim(o.second, "&");
this.parameters = new URLVariables();
if (o.second != "")
{
try
{
this.parameters.decode(o.second);
}
catch (e:Error)
{
trace("Warning: cannot decode URL parameters. " + e.message + " " + o.second);
}
}
rest = o.first
o = this.splitSingle(rest, "/");
if (o.second != "")
{
this.path = "/" + o.second;
}
rest = o.first;
o = this.splitSingle(rest, ":");
if (o.second != "")
{
this.port = parseInt(o.second);
}
else
{
switch (this.protocol)
{
case "https":
this.port = 443;
break;
case "http":
this.port = 80;
break;
case "ssh":
this.port = 22;
break;
case "ftp":
this.port = 21;
break;
default:
this.port = 0;
}
}
this.domain = o.first;
}
public function getDomain():String
{
return this.domain;
}
public function getProtocol():String
{
return this.protocol;
}
public function getPath():String
{
return this.path;
}
public function getPort():int
{
return this.port;
}
public function getBookmark():String
{
return this.bookmark;
}
public function getParameters():URLVariables
{
return this.parameters;
}
}
}
Example usage
try {
var myUrl:Url = new Url("protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes");
trace("Protocol: " + myUrl.getProtocol());
trace("Domain: " + myUrl.getDomain());
trace("Path: " + myUrl.getPath());
trace("What you want: " + myUrl.getPath().split("/").splice(2).join("/") );
} catch (e:Error) {
trace("Warning: cannot parse url");
}
Output
Protocol: protocol
Domain: mydomain.com
Path: /something/morethings/this_is_what_i_want/even_if_it_has_slashes
What you want: morethings/this_is_what_i_want/even_if_it_has_slashes
Description
The init function checks with the regular expression if the given url starts with some letters (the protocol) followed by a colon, two slashes and more characters.
If the url contains a hash letter, everything behind its fist occurrence is taken as a bookmark
If the url contains a question mark, everything behind its fist occurrence is taken as key=value variables and parsed by the URLVariables class.
If the url contains a slash, everything behind its first occurrence is taken as the path
If the rest (everything between the last protocol slash and the first slash of the path) contains a colon, everything behind it will be converted to an integer and taken as the port. If the port is not set, a default will be set in dependency of the protocol
The rest is the domain
For answering your question, I use the path of the given url, split it by slash, cut of the 'something' and join it by slash.

Youtube Api JSON arranges results incorrectly

I'm using the Video Picker app (by LockeVN: https://github.com/lockevn/YouTube-video-picker), and the results i'm getting are not ordered like they are on the youtube website (or any other search app on github).
FOR EXAMPLE:
I type in : 'Bizarre Inc feat Angie Brown I'm Gonna Get You'.
The first video I get in youtube is: 'Bizarre Inc feat Angie Brown - I'm Gonna Get You (1992)'.
The first video I get in Video Picker app is:'BIZARRE INC - I'M GONNA GET YOU (SAVERY & MILLER MASHUP MIX)'
NOTE: Both are set to orderby=relevance and the video ordering changes when I change max-results; only when max-result is set to 1, the result is correctly ordered.
Anyone know how this can be fixed?
CODE:
(function ($) {
$.fn.YouTubePicker = function (options) {
// default option
var defaults = {
MaxResults: 10 /* number of YouTube results, per "page" */
, OrderBy: 'relevance' /* what to order the results by */
, Author: null /* Author of the video */
, PlayerNumberOp: 1
, ShowNumOfViews: true /* show number of views for the video */
, Thumbnail: 'small' /* small: 120x90 | large: 480 x 360 */
, ControlIdSuffix: '' /* should give the unique string here if you have multiply of YouTubePicker.
Using elements in this plugin will fetch by "id + ControlIdSuffix" */
, ControlQueryHolder: '.YouTubePickerQuery' /* selector to take a element to be query holder (where we take string to query YouTube) */
, ControlSearchButton: '.YouTubePickerSearch' /* selector to take a element to be SearchButton. Click this element to start search. */
, ControlVideoPlayerHolder: '.YouTubePickerVideoPlayer' /* selector to take a element to render VideoPlayer */
, ControlVideoTitleHolder: '.YouTubePickerVideoTitle'
, ControlVideoList: '.YouTubePickerVideoList' /* selector to take a element to render VideoList */
, ControlSelectedUrlHolder: '.YouTubePickerSelectedUrl' /* When user click to select a video, assign the video's url to this input */
, InitVideoUrl: '' /* Init if no search query existed, you can put YouTubeVideoId here or the full Url */
, PlayerWidth: '240' /* setting for player */
, PlayerHeight: '220' /* setting for player */
, AutoPlay: false /* AutoPlay video right after user click an item in the list */
, ShowRelated: false /* show relate video after finish playing */
, AllowFullScreen: true /* enable FullScreen button of Player */
, EnableJsApi: true /* enable Javascript Api*/
};
options = $.extend(defaults, options);
return this.each(function () {
var $container = $(this);
$(options.ControlSearchButton).click(function () {
/// <summary>
/// handler click on search button
/// </summary>
var requestUrl = 'http://gdata.YouTube.com/feeds/api/videos?alt=json&max-results=' + options.MaxResults;
try {
_RequestYouTubeVideos(requestUrl);
} catch (ex) { }
return false;
});
$(options.ControlQueryHolder).keydown(function (event) {
/// <summary>
/// handler press Enter in query textbox
/// </summary>
if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
$(options.ControlSearchButton).trigger('click');
return false;
}
else {
return true;
}
});
//-------------------------------------------------------//
// take the init video and play it if any
// ERASED THIS PART
// $(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(options.InitVideoUrl)));
// _AssignValueToDivOrTextBox(options.ControlSelectedUrlHolder, options.InitVideoUrl);
$('a.navigation').click(function () {
/// <summary>
/// rebind the list whenever user click to change page
/// </summary>
try {
_RequestYouTubeVideos($(this).attr('href'));
} catch (ex) { }
return false;
});
/**
* Util function, assign value to element. Element can be div, span, or input
*/
function _AssignValueToDivOrTextBox(selectorToElement, valueToAssign) {
try {
$(selectorToElement).val(valueToAssign);
} catch (ex) { }
try {
$(selectorToElement).text(valueToAssign);
} catch (ex) { }
}
function _RequestYouTubeVideos(requestUrl) {
/// <summary>
/// fire the jsonp request to get data from YouTube Search API
/// </summary>
var query = $(options.ControlQueryHolder).val();
if (options.Author != null) {
requestUrl += '&author=' + options.Author;
}
if (options.OrderBy != null) {
requestUrl += '&orderby=' + options.OrderBy;
}
if (query != null) {
requestUrl += '&q=' + query;
}
$.ajax({
type: "GET",
url: requestUrl,
cache: false,
dataType: 'jsonp',
global: false,
success: _OnYouTubeSuccess,
error: function (result) {
$(options.ControlVideoList).html('<p>Please fill in a search term</p>');
}
,
ajaxComplete: function (data) {
return false;
}
});
}
function _BuildNavigation(feed) {
/// <summary>
/// Build the navigation link Prev and Next base on the return url in the feed (if existed)
/// </summary>
if (feed.link) {
var nextLink = null;
var prevLink = null;
for (var i = 0; i < feed.link.length; i++) {
var link = feed.link[i];
if (link.rel == 'next') {
nextLink = link.href;
}
else if (link.rel == 'previous') {
prevLink = link.href;
}
}
if (nextLink) {
$('.navigation.next').attr('href', nextLink).show();
}
else {
$('.navigation.next').hide();
}
if (prevLink) {
$('.navigation.prev').attr('href', prevLink).show();
}
else {
$('.navigation.prev').hide();
}
}
}
function formatSecondsAsTime(secs) {
var hr = Math.floor(secs / 3600);
var min = Math.floor((secs - (hr * 3600)) / 60);
var sec = Math.floor(secs - (hr * 3600) - (min * 60));
if (hr < 10) {
hr = "0" + hr;
}
if (min < 10) {
min = "0" + min;
}
if (sec < 10) {
sec = "0" + sec;
}
if (hr) {
hr = "00";
}
return hr + ':' + min + ':' + sec;
}
function _ParseYouTubeFeedItem(feedData) {
/// <summary>
/// Extract what we want from YouTube feedData
/// </summary>
var dto = [];
dto.id = _StripFeature(feedData.link[0].href.substring(feedData.link[0].href.indexOf('=') + 1, feedData.link[0].href.length));
dto.url = feedData.link[0].href;
dto.title = feedData.title.$t;
if (options.Thumbnail == 'large') {
var index = 0; // first thumb is large size
} else {
var index = feedData.media$group.media$thumbnail.length - 1; // take the last small thumb
}
dto.thumbnail = feedData.media$group.media$thumbnail[index].url;
dto.description = feedData.media$group.media$description.$t;
dto.author = feedData.author[0].name.$t;
dto.duration = formatSecondsAsTime(feedData.media$group.media$content[0].duration);
if (feedData.yt$statistics) {
dto.views = feedData.yt$statistics.viewCount;
}
else if (!feedData.yt$statistics) {
dto.views = '0';
}
return dto;
}
/**
* Process the json result, render the list
*/
function _OnYouTubeSuccess(result) {
var feed = result.feed;
var rfeed = feed.entry || [];
var relVideos = [];
var $ctrVideoList = $(options.ControlVideoList);
// build the navigation
_BuildNavigation(feed);
if (rfeed.length > 0) {
$(rfeed).each(function (i) {
/// <summary>
/// from feeditem from YouTube, build the video data object
/// </summary>
relVideos[i] = _ParseYouTubeFeedItem(rfeed[i]);
}).ready(function () {
relVideos.sort(_ArraySort);
var $itemsHtml = $('<div>'); // temporary DOM node to append VideoItem to
$(relVideos).each(function (i) {
/// <summary>
/// Create each list item
/// </summary>
$itemsHtml.append('<li class="VideoItem">');
videoItem = $itemsHtml.find('.VideoItem:last');
videoItem.append('<div class="VideoThumb">');
videoThumb = videoItem.find('.VideoThumb');
$('<a>').addClass('YouTubelink').attr('href', relVideos[i].url).append('<img src="' + relVideos[i].thumbnail + '">').appendTo(videoThumb);
videoItem.append('<div class="VideoInfo">');
videoInfo = videoItem.find('.VideoInfo');
videoInfo.append('<strong>' + relVideos[i].title + ' </strong><br /><span class="VideoNumOfViews">' + relVideos[i].views + ' views</span><br /><span></span>' + relVideos[i].duration + '<br />');
});
// clear the list
$ctrVideoList.empty().append($itemsHtml.children());
});
// load inital video after finish rendering the list
// take the first video in the list, take it link, take it href, assign to the Player
// ERASED THIS PART
//var firstVid = $ctrVideoList.children("li:first-child").addClass("selected").find("a").eq(1).attr("href");
//$(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(firstVid)));
$ctrVideoList.find("li a").unbind('click').bind('click', function () {
/// <summary>
/// load video on click of a in li
/// </summary>
try {
var selectedUrl = $(this).attr("href");
// return the selectedUrl to outside (try catch to avoid error in IE)
_AssignValueToDivOrTextBox(options.ControlSelectedUrlHolder, selectedUrl);
$(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(selectedUrl)));
// DIT IS EEN TEST
$(options.ControlVideoTitleHolder + "").html(_GetTitleHtml(_GetYouTubeIdFromUrl(selectedUrl)));
$(this).parent().parent().parent("ul").find("li.selected").removeClass("selected");
$(this).parent().parent("li").addClass("selected");
} catch (ex) { }
return false;
});
} else {
/* if we have no YouTube videos returned, let's tell user */
$ctrVideoList.html('<p>There is no result</p>');
}
} // end _OnYouTubeSuccess
function _ArraySort(a, b) {
if (a.title < b.title) {
return -1;
}
else if (a.title > b.title) {
return 1;
}
else {
return 0;
}
}
function _StripFeature(vidID) {
var featureLoc = vidID.indexOf('&feature=YouTube_gdata');
if (featureLoc >= 0) {
return vidID.substring(0, featureLoc);
} else {
return vidID;
}
}
/**
* Create a Player HTML code to play an YouTubeID, and return it HTML string
*/
function _GetPlayerHtml(YouTubeVideoId) {
// if YouTubeVideoId is null or empty, we provide an empty div with same dimension of the Player
// This will fix a bug of IE (IE will load the swf forever if object movie is empty and/or embbed src is empty
if (!YouTubeVideoId) {
return '<div style="width:240px;height:220px">';
}
var html = '';
var PlayerNumber = options.PlayerNumberOp;
html += '<object height="220" width="240">';
html += '<param name="movie" value="http://www.YouTube.com/v/'+YouTubeVideoId+'?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1"> </param>';
html += '<param name="wmode" value="transparent"> </param>';
// I HAVE CHANGED THIS
html += '<iframe onload="floaded'+PlayerNumber+'()" id="player'+PlayerNumber+'" width="240" height="220" src="http://www.youtube.com/embed/'+YouTubeVideoId+'?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1" frameborder="0" allowfullscreen> </iframe>';
html += '</object>';
return html;
};
function _GetTitleHtml(YouTubeVideoId) {
var html = '';
var PlayerNumber = options.PlayerNumberOp;
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+YouTubeVideoId+'?v=2&alt=jsonc',function(data,status,xhr){
var video_title1=data.data.title;
var finaltext1="<div id='title1'><h5 class='redtext'>USER SELECTED</h5><h5>"+video_title1+"</h5></div>";
$('#YouTubePickerVideoTitle'+PlayerNumber+'').html(finaltext1);
});
return html;
};
function _GetYouTubeIdFromUrl(url) {
/// <summary>
/// use RegEx too grab a YouTube id from a (clean, no querystring) url (thanks to http://jquery-howto.blogspot.com/2009/05/jYouTube-jquery-YouTube-thumbnail.html)
/// <return>empty string if cannot match.</return>
/// </summary>
if (url && url != '') {
try {
var ytid = url.match("[\\?&]v=([^&#]*)");
ytid = ytid[1];
return ytid;
}
catch (ex) { }
}
return '';
};
});
};
})(jQuery);
Deniz.
I'm not sure but guess Youtube uses your preferences to filter video searches.
Try other kind of filter and see what you get.

My pattern is wrong, how do I make it DRY?

So I got this TitleWindow based Flex application where these windows are called by static functions written in them.
This is how it looks like when an entity needs do be created or edited from a DataGrid:
private function incluir():void {
NavioForm.incluir(dg.dataProvider);
}
private function atualizar():void {
NavioForm.atualizar(dg.dataProvider, dg.selectedIndex);
}
It's working perfectly from this side.
But since I used static functions, the code is starting to get a bit repetitive, as we can see on the examples below:
[Script tag of a CRUD form(incluir == include, atualizar == update, excluir == delete)]
...
[Bindable] private var navio:Navio;
public static function incluir(dataList:IList):void {
var form:NavioForm = new NavioForm();
form.action = FormWindow.ACTION_NEW + Navio.name;
form.navio = new Navio();
form.navio.lastUpdate = new Date();
form.result = function():void {
PortoService.obj.persistirNavio(form.navio).result(function(navio:Navio):void {
dataList.addItem(navio);
form.close();
}).fault(function(event:FaultEvent):void {
if(event.fault.faultString == 'duplicate key') {
Util.showError("This vessel's IMO is already present in our database.");
} else throw event.fault;
});
};
PopUp.add(form);
}
public static function atualizar(dataList:IList, index:int):void {
var form:NavioForm = new NavioForm();
form.action = FormWindow.ACTION_UPDATE + Navio.name;
form.imoRecieved = true;
form.navio = dataList[index];
PortoService.obj.obter(Navio, form.navio.key).result(function(navio:Navio):void {
form.navio = navio;
form.navio.lastUpdate = new Date();
});
form.result = function():void {
PortoService.obj.persistir(form.navio).result(function(navio:Navio):void {
dataList[index] = navio;
form.close();
}).fault(function(event:FaultEvent):void {
if(event.fault.faultString == 'duplicate key') {
Util.showError("This vessel's IMO is already present in our database.");
} else throw event.fault;
});
};
PopUp.add(form);
}
...
Script tag of another CRUD form:
...
[Bindable] private var vesselType:VesselType;
public static function incluir(dataList:IList):void {
var form:VesselTypeForm = new VesselTypeForm();
form.action = FormWindow.ACTION_NEW + VesselType.name;
form.vesselType = new VesselType();
form.result = function():void {
CoreService.obj.persistir(form.vesselType).result(function(type:VesselType):void {
dataList.addItem(type);
form.close();
});
};
PopUp.add(form);
}
public static function atualizar(dataList:IList, index:int):void {
var form:VesselTypeForm = new VesselTypeForm();
form.action = FormWindow.ACTION_UPDATE + VesselType.name;
form.vesselType = Util.clone(dataList[index]);
form.result = function():void {
CoreService.obj.persistir(form.vesselType).result(function(type:VesselType):void {
dataList[index] = type;
form.close();
});
};
form.deleteClick = function():void {
CoreService.obj.excluir(form.vesselType.key).result(function():void {
dataList.removeItemAt(index);
form.close();
});
};
PopUp.add(form);
}
So, is there a design pattern or any other technique to make this work?
You could make a crud component that you instantiate with all of the dynamic stuff such as the data provider location and it broadcasts events (or signals) that you assign appropriate listeners to.

firebug saying not a function

<script type = "text/javascript">
var First_Array = new Array();
function reset_Form2() {document.extraInfo.reset();}
function showList1() {document.getElementById("favSports").style.visibility="visible";}
function showList2() {document.getElementById("favSubjects").style.visibility="visible";}
function hideProceed() {document.getElementById('proceed').style.visibility='hidden';}
function proceedToSecond ()
{
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="visible";
document.getElementById("favSports").style.visibility="hidden";
document.getElementById("favSubjects").style.visibility="hidden";
}
function backToFirst () {
document.getElementById("div1").style.visibility="visible";
document.getElementById("div2").style.visibility="hidden";
document.getElementById("favSports").style.visibility="visible";
document.getElementById("favSubjects").style.visibility="visible";
}
function reset_Form(){
document.personalInfo.reset();
document.getElementById("favSports").style.visibility="hidden";
document.getElementById("favSubjects").style.visibility="hidden";
}
function isValidName(firstStr) {
var firstPat = /^([a-zA-Z]+)$/;
var matchArray = firstStr.match(firstPat);
if (matchArray == null) {
alert("That's a weird name, try again");
return false;
}
return true;
}
function isValidZip(zipStr) {
var zipPat =/[0-9]{5}/;
var matchArray = zipStr.match(zipPat);
if(matchArray == null) {
alert("Zip is not in valid format");
return false;
}
return true;
}
function isValidApt(aptStr) {
var aptPat = /[\d]/;
var matchArray = aptStr.match(aptPat);
if(matchArray == null) {
if (aptStr=="") {
return true;
}
alert("Apt is not proper format");
return false;
}
return true;
}
function isValidDate(dateStr) {
//requires 4 digit year:
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
var matchArray = dateStr.match(datePat);
if (matchArray == null) {
alert("Date is not in a valid format.");
return false;
}
return true;
}
function checkRadioFirst() {
var rb = document.personalInfo.salutation;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please specify a salutation");
return false;
}
function checkCheckFirst() {
var rb = document.personalInfo.operatingSystems;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please specify an operating system") ;
return false;
}
function checkSelectFirst() {
if ( document.personalInfo.sports.selectedIndex == -1)
{
alert ( "Please select a sport" );
return false;
}
return true;
}
function checkRadioSecond() {
var rb = document.extraInfo.referral;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please select form of referral");
return false;
}
function checkCheckSecond() {
var rb = document.extraInfo.officeSupplies;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please select an office supply option");
return false;
}
function checkSelectSecond() {
if ( document.extraInfo.colorPick.selectedIndex == 0 ) {
alert ( "Please select a favorite color" );
return false;
}
return true;
}
function check_Form(){
var retvalue = isValidDate(document.personalInfo.date.value);
if(retvalue) {
retvalue = isValidZip(document.personalInfo.zipCode.value);
if(retvalue) {
retvalue = isValidName(document.personalInfo.nameFirst.value);
if(retvalue) {
retvalue = checkRadioFirst();
if(retvalue) {
retvalue = checkCheckFirst();
if(retvalue) {
retvalue = checkSelectFirst();
if(retvalue) {
retvalue = isValidApt(document.personalInfo.aptNum.value);
if(retvalue){
document.getElementById('proceed').style.visibility='visible';
var rb = document.personalInfo.salutation;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
var salForm = rb[i].value;
}
}
var SportsOptions = "";
for(var j=0;j<document.personalInfo.sports.length;j++){
if ( document.personalInfo.sports.options[j].selected){
SportsOptions += document.personalInfo.sports.options[j].value + " ";
}
}
var SubjectsOptions= "";
for(var k=0;k<document.personalInfo.subjects.length;k++){
if ( document.personalInfo.subjects.options[k].selected){
SubjectsOptions += document.personalInfo.subjects.options[k].value + " ";
}
}
var osBox = document.personalInfo.operatingSystems;
var OSOptions = "";
for(var y=0;y<osBox.length;y++) {
if(osBox[y].checked) {
OSOptions += osBox[y].value + " ";
}
}
First_Array[0] = salForm;
First_Array[1] = document.personalInfo.nameFirst.value;
First_Array[2] = document.personalInfo.nameMiddle.value;
First_Array[3] = document.personalInfo.nameLast.value;
First_Array[4] = document.personalInfo.address.value;
First_Array[5] = document.personalInfo.aptNum.value;
First_Array[6] = document.personalInfo.city.value;
for(var l=0; l<document.personalInfo.state.length; l++) {
if (document.personalInfo.state.options[l].selected) {
First_Array[7] = document.personalInfo.state[l].value;
}
}
First_Array[8] = document.personalInfo.zipCode.value;
First_Array[9] = document.personalInfo.date.value;
First_Array[10] = document.personalInfo.phone.value;
First_Array[11] = SportsOptions;
First_Array[12] = SubjectsOptions;
First_Array[13] = OSOptions;
alert("Everything looks good.");
document.getElementById('validityButton').style.visibility='hidden';
}
}
}
}
}
}
}
}
/*function formAction2() {
var retvalue;
retvalue = checkRadioSecond();
if(!retvalue) {
return retvalue;
}
retvalue = checkCheckSecond();
if(!retvalue) {
return retvalue;
}
return checkSelectSecond() ;
} */
</script>
This is just a sample of the code, there are alot more functions, but I thought the error might be related to surrounding code. I have absolutely no idea why, as I know all the surrounding functions execute, and First_Array is populated.
However when I click the Proceed to Second button, the onclick attribute does not execute because Firebug says proceedToSecond is not a function
button code:
<input type="button" id="proceed" name="proceedToSecond" onclick="proceedToSecond();" value="Proceed to second form">
I had the same problem, and it's because you have a form with the same name as your function. JavaScript doesn't seem to be able to distinguish between the two, so you get the "not a function" error.
Maybe there is an error in your Javascript before that snippet given by you. If so, the rest will not be parsed by Firefox and then your function will not be defined.
The problem was resolved by changing proceedToSecond() to doIt() in both the call and the function name. I have no idea why
Hmm... I always used javascript:function_name() instead of function_name() because a few times the javascript didn't run. The name tag for the html snippet might have to be changed to a slightly different name because javascript might be getting it mixed up. Can you show us the entire javascript file because there may be a mistake/syntax error somewhere at the bottom/top.
It works on my computer, Firefox 3.5.5, Firebug 1.4.3, when inserting your code into an empty html document (<html><head/><body> code </body></html>)
Maybe there is another bug somewhere in your DOM, or in some of your other functions?
Could you possibly paste the entire source here, or maybe on a pastebin site?