I'm using the 'Compilation.xml' template from the TVMLCatalog
I'd like to add a button click event to a 'listItemLockup'
<listItemLockup>
<ordinal minLength="2" class="ordinalLayout">0</ordinal>
<title>Intro</title>
<subtitle>00</subtitle>
<decorationLabel>(3:42)</decorationLabel>
</listItemLockup>
I've tried adding:
App.onLaunch = function(options) {
var templateURL = 'http://localhost:8000/hello.tvml';
var doc = getDocument(templateURL);
//doc.addEventListener("select", function() { alert("CLICK!") }, false);
var listItemLockupElement = doc.getElementsByTagName("listItemLockup");
listItemLockupElement.addEventListener("select", function() { alert("CLICK!") }, false);
}
addEventListener
void addEventListener (in String type, in Object listener, in optional Object extraInfo)
Is "select" the correct type?
I've been using the following tutorials
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-with-swift/
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-part-2/
Update
I'm getting an error
ITML <Error>: doc.getElementsByTagName is not a function. (In 'doc.getElementsByTagName("listItemLockup")', 'doc.getElementsByTagName' is undefined) - http://localhost:8000/main.js - line:27:58
I tried adding this to the 'onLaunch'
var listItemLockupElements = doc.getElementsByTagName("listItemLockup");
for (var i = 0; i < listItemLockupElements.length; i++) {
//var ele = listItemLockupElements[i].firstChild.nodeValue;
listItemLockupElements[i].addEventListener("select", function() { alert("CLICK!") }, false);
}
I'll see about the error first
Cross Post: https://forums.developer.apple.com/thread/17859
More common example I have seen by Apple is to define a single overall listener like:
doc.addEventListener("select", Presenter.load.bind(Presenter));
In your xml, assign unique ids to elements, or give them ways to identify them.
For example, the beginning would be something like:
load: function(event) {
var self = this,
ele = event.target,
attr_id = ele.getAttribute("id"),
audioURL = ele.getAttribute("audioURL"),
videoURL = ele.getAttribute("videoURL")
And then you can do whatever you want with your item.
if(audioURL && (event.type === "select" || event.type === "play")) {
//
}
My advice would be to study the Presenter.js file more carefully for this pattern.
Edit:
Answering your "Update" related to doc.getElementsByTagName is not a function. "doc" does not actually exist, but the general pattern is to get it with
var doc = getActiveDocument();
I assumed you would know the above.
Does that fix it?
var listItemLockupElement = doc.getElementsByTagName("listItemLockup”);
In this case, the listItemLockupElement is a NodeList, not an element. You can either iterate through the list and add an event listener to each listItemLockup, or you could add the event listener to the containing element.
When addressing items in a NodeList, you use the item(i) method rather than the standard array access notation:
listItemLockupElements.item(i).addEventListener("select", function() { })
See: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/item
Adding event listeners is straightforward if you're using atvjs framework.
ATV.Page.create({
name: 'mypage',
template: your_template_function,
data: your_data,
events: {
select: 'onSelect',
},
// method invoked in the scope of the current object and
// 'this' will be bound to the object at runtime
// so you can easily access methods and properties and even modify them at runtime
onSelect: function(e) {
let element = e.target;
let elementType = element.nodeName.toLowerCase();
if (elementType === 'listitemlockup') {
this.doSomething();
}
},
doSomething: function() {
// some awesome action
}
});
ATV.Navigation.navigate('mypage');
Disclaimer: I am the creator and maintainer of atvjs and as of writing this answer, it is the only JavaScript framework available for Apple TV development using TVML and TVJS. Hence I could provide references only from this framework. The answer should not be mistaken as a biased opinion.
Related
I'm trying to figure out how to execute some js code when an element is removed from the page:
Something in prototype like:
$('custom-div').observe('remove', function(event) {
// Handle the event
});
Does anything like this exist?
In modern browsers, you can use a MutationObserver. Here's code that will call a callback when a DOM element is removed from it's current location:
function watchRemove(el, fn) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var item;
if (mutation.type === "childList" && mutation.removedNodes) {
for (var i = 0; i < mutation.removedNodes.length; i++) {
item = mutation.removedNodes[i];
if (item === el) {
// clear the observer
observer.disconnect();
fn.call(item, item);
break;
}
}
}
});
});
observer.observe(el.parentNode, {childList: true});
return observer;
}
And, a working demo: http://jsfiddle.net/jfriend00/naft3qeb/
This watches the parent for changes to its direct children and calls the callback if the specific DOM element passed in is removed.
The observer will remove itself when the DOM element is removed or watchRemove() returns the observer instance which you can call .disconnect() on at any time to stop the watching.
Here's a jQuery plug-in that uses this functionality:
jQuery.fn.watchRemove = function(fn, observers) {
return this.each(function() {
var o = watchRemove(this, fn);
if (observers) {
observers.push(o);
}
});
}
In this case, it accepts an optional array object as an argument that will be filled with all the observer objects (only necessary to pass this if you want to be able to stop the watching yourself on any given item).
I'm completely baffled. I have some very simple code that takes an object and converts it to JSON.
var vl = JSON.stringify(this.visibleLayers);
This always returns undefined, that is, the variable vl has an undefined value. Yet when I check
JSON.stringify(this.visibleLayers);
in the console, it returns the string I expect. this.visibleLayers is an object, not an array. What could be going on?
EDIT: Adding more code
Below the is the method this is being called in. This is using the Dojo AMD style. Bascially I loop through my map layers and their sublayers to indicate, for each, whether or not the layer is currently visible in the map. So I end up with an object that looks like
{"streets":true,"highways":true,...}
submitExportCustomMap: function() {
domStyle.set("pdfRequestFinished", "display", "none");
domStyle.set("pdfRequestError", "display", "none");
domStyle.set("pdfRequest", "display", "block");
registry.byId("printButton").set("disabled", true);
this.visiblelayers = {};
var _this = this;
array.forEach(map.layerIds, function(layer, i1) {
var ml = map.getLayer(layer);
_this.visiblelayers[ml.id] = ml.visible;
var s = array.forEach(ml.layerInfos, function(sublayer, i2){
if (array.indexOf(ml.visibleLayers, sublayer.id.toString()) !== -1 && ml.visible) {
_this.visiblelayers[sublayer.name] = true;
}
else {
_this.visiblelayers[sublayer.name] = false;
}
});
});
this.prepareCommonParameters();
var vl = JSON.stringify(this.visibleLayers);
var params = {
"xMin": this.extent.xmin,
"yMin": this.extent.ymin,
"xMax": this.extent.xmax,
"yMax": this.extent.ymax,
"Spatial_Reference": this.spatRef,
"Map_Scale": this.mapScale,
"Visiblelayers": vl,
"Layout": this.layout,
"Map_Title": dom.byId("mapTitle").value,
"PointGraphics": graph.getFeatureSet("point"),
"LineGraphics": graph.getFeatureSet("polyline"),
"PolyGraphics": graph.getFeatureSet("polygon")
};
this.cmgp.submitJob(params, lang.hitch(this, this.pdfCompleteCallbackCM), lang.hitch(this, this.pdfStatusCallback), lang.hitch(this, this.pdfErrorCallback));
},
Boy do I feel stupid! It turns out I somehow misstyped visibleLayers. Declaring the variable I called is visiblelayers, with a lower case l. Making the stringify call I use visibleLayers, with a capital L. Making them consistent solved all the problems. D'Oh!
i use fetch from backbone.js to load a json model but success will not hit.
var DialogModel = Backbone.Model.extend({
url : function() {
return '/messages/getDialog';
},
parse : function(res) {
return res.dialog;
}
});
var DialogView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
var onDataHandler = function() {
this.render();
};
this.model = new DialogModel();
this.model.fetch({ success : onDataHandler});
},
render: function(){
var data = {
dialogModel : this.model
};
var form = new Backbone.Form({
model: data
});
$(this.el).html(form.render().el);
}
});
What happens now:
DialogView initialize is called.
this.model.fetch is called but the onDataHandler function will not be hit if success.
/messages/getDialog throws a json file back.
The json file is loading well as i can see in the network browser.
Thanks for your help!
Oleg
The problem you're having is due to a typical JS gotcha and not related to Backbone itself. Try
var that = this;
this.model.fetch({
success : function () {
that.render();
}
});
The way you're currently passing onDataHandler is problematic as it will cause this to refer to the global object instead of the DialogView, when the function is called.
This fiddle demonstrates the problematic version vs one that works.
(You may also want to take a look at JS strict mode which can shield you from this type of errors.)
Even better is to listen for an event:
this.model.on("sync", this.render).fetch();
I ran across this question while looking for something else, but the currently accepted answer drives me nuts. There's no good reason to be sprinkling this and that all over your code. Backbone (underscore) includes a context parameter that you can bind to.
that = this makes no sense. If you must implement obsolete 2007-era Crockford patterns, then say var self = this. Saying that = this is like saying left = right. Everyone Stop.
Method UiInstance.getElementById(ID) always returns GenericWidget object, even if ID does not exist.
Is there some way how to find out that returned object does not exist in my app, or check whether UI contains object with given ID?
Solution for UI created with GUI builder:
function getSafeElement(app, txtID) {
var elem = app.getElementById(txtID);
var bExists = elem != null && Object.keys(elem).length < 100;
return bExists ? elem : null;
}
It returns null if ID does not exist. I didn't test all widgets for keys length boundary, so be careful and test it with your GUI.
EDIT: This solution works only within doGet() function. It does not work in server handlers, so in this case use it in combination with #corey-g answer.
This will only work in the same execution that you created the widget in, and not in a subsequent event handler where you retrieve the widget, because in that case everything is a GenericWidget whether or not it exists.
You can see for yourself that the solution fails:
function doGet() {
var app = UiApp.createApplication();
app.add(app.createButton().setId("control").addClickHandler(
app.createServerHandler("clicked")));
app.add(app.createLabel(exists(app)));
return app;
}
function clicked() {
var app = UiApp.getActiveApplication();
app.add(app.createLabel(exists(app)));
return app;
}
function exists(app) {
var control = app.getElementById("control");
return control != null && Object.keys(control).length < 100;
}
The app will first print 'true', but on the click handler it will print 'false' for the same widget.
This is by design; a GenericWidget is a "pointer" of sorts to a widget in the browser. We don't keep track of what widgets you have created, to reduce data transfer and latency between the browser and your script (otherwise we'd have to send up a long list of what widgets exist on every event handler). You are supposed to keep track of what you've created and only "ask" for widgets that you already know exist (and that you already know the "real" type of).
If you really want to keep track of what widgets exist, you have two main options. The first is to log entries into ScriptDb as you create widgets, and then look them up afterwards. Something like this:
function doGet() {
var app = UiApp.createApplication();
var db = ScriptDb.getMyDb();
// You'd need to clear out old entries here... ignoring that for now
app.add(app.createButton().setId('foo')
.addClickHandler(app.createServerHandler("clicked")));
db.save({id: 'foo', type: 'button'});
app.add(app.createButton().setId('bar'));
db.save({id: 'bar', type: 'button'});
return app
}
Then in a handler you can look up what's there:
function clicked() {
var db = ScriptDb.getMyDb();
var widgets = db.query({}); // all widgets
var button = db.query({type: 'button'}); // all buttons
var foo = db.query({id: 'foo'}); // widget with id foo
}
Alternatively, you can do this purely in UiApp by making use of tags
function doGet() {
var app = UiApp.createApplication();
var root = app.createFlowPanel(); // need a root panel
// tag just needs to exist; value is irrelevant.
var button1 = app.createButton().setId('button1').setTag("");
var button2 = app.createButton().setId('button2').setTag("");
// Add root as a callback element to any server handler
// that needs to know if widgets exist
button1.addClickHandler(app.createServerHandler("clicked")
.addCallbackElement(root));
root.add(button1).add(button2);
app.add(root);
return app;
}
function clicked(e) {
throw "\n" +
"button1 " + (e.parameter["button1_tag"] === "") + "\n" +
"button2 " + (e.parameter["button2_tag"] === "") + "\n" +
"button3 " + (e.parameter["button3_tag"] === "");
}
This will throw:
button1 true
button2 true
button3 false
because buttons 1 and 2 exist but 3 doesn't. You can get fancier by storing the type in the tag, but this suffices to check for widget existence. It works because all children of the root get added as callback elements, and the tags for all callback elements are sent up with the handler. Note that this is as expensive as it sounds and for an app with a huge amount of widgets could potentially impact performance, although it's probably ok in many cases especially if you only add the root as a callback element to handlers that actually need to verify the existence of arbitrary widgets.
My initial solution is wrong, because it returns false exist controls.
A solution, based on Corey's answer, is to add the setTag("") method and here is ready to use code. It is suitable for event handlers only, because uses tags.
function doGet() {
var app = UiApp.createApplication();
var btn01 = app.createButton("control01").setId("control01").setTag("");
var btn02 = app.createButton("control02").setId("control02").setTag("");
var handler = app.createServerHandler("clicked");
handler.addCallbackElement(btn01);
handler.addCallbackElement(btn02);
btn01.addClickHandler(handler);
btn02.addClickHandler(handler);
app.add(btn01);
app.add(btn02);
return app;
}
function clicked(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel("control01 - " + controlExists(e, "control01")));
app.add(app.createLabel("control02 - " + controlExists(e, "control02")));
app.add(app.createLabel("fake - " + controlExists(e, "fake")));
return app;
}
function controlExists(e, controlName) {
return e.parameter[controlName + "_tag"] != null;
}
Hi there i have this code snippet I need to get working with MooTools 1.3 :
this.fn = function (e, cal) {
var e = new Event(e);
var el = e.target;
var stop = false;
while (el != document.body && el.nodeType == 1) {
if (el == this.calendar) { stop = true; }
this.calendars.each(function (kal) {
if (kal.button == el || kal.els.contains(el)) { stop = true; }
});
if (stop) {
e.stop();
return false;
}
else { el = el.parentNode; }
}
this.toggle(cal);
}.create({
'arguments': cal,
'bind': this,
'event': true
}); <-- THIS CREATE METHOD DOES NOT WORK
Can someone help me whit this ?
After create function was deprecated, you need to "manually" recreate the usage.
In this case, you are creating a function that will be an event listener and binding it later in the code (this is Aeron Glemann's calendar).
So what you need to do, is put this function in addEvent you find directly below it, like this.
document.addEvent('mousedown', function(e, cal) {
[...]
}.bind(this));
Also, there's a removeEvent call at the begining of the function you're currently editing (the toggle function) that will no longer work since this function no longer has a name, replace it with removing all events on mousedown, worked for me.
document.removeEvents('mousedown');
as i said on the mootools user mailing list, i don't know about the "perfect" way, but in the meantime you can always (if you don't want to use the 1.2 compat version)
inspire yourself from the implementation of the function for 1.2 compat :
https://github.com/mootools/mootools-core/blob/025adc07dc7e9851f30b3911961d43d525d83847/Source/Types/Function.js#L74
I have to admit the doc for 1.3 only mention that this method is deprecated.