leaflet .bindPopup() not working after page change - ionic-framework

I am working on leaflet map and showing markers on it. on click of marker I am opening the popup and on click of that navigating it to another page, this all works fine but when I click back from the navigated page to map then the .bindPopup() is not working and I am not able to open the popup again.
here is my code:
var marker = leaflet.circleMarker([marker.latitude, marker.longitude], { renderer, radius: 8, weight: 1, color: '#fff', fillColor: markerColor, fillOpacity: 1 })
.addTo(this.map)
.bindPopup(marker.id + '<br/>' + marker.status + '<br/>');
marker.on('click', (e) => {
var popup = e.target.getPopup();
this.issueServiceProvider.getIssue(marker.id, false).subscribe((result) => {
var div = leaflet.DomUtil.create('div', 'command');
div.innerHTML = marker.id + '<br/>' + marker.status + '<br/>' + result.description + '<br/><a id = "command">More Details</a> <br/>';
popup.setContent(div);
leaflet.DomEvent.addListener(div, 'click', () => {
this.navCtrl.push(Constants.Page.IssueDetails, { markerId: marker.id }, Constants.Animation['TransitionForward']);
});
}, (err) => {
console.error('Error' + err);
});
});
How could I make it work?

This popup works, but does not reference your specific function. Try this and then add your function call once the basic setup is complete.
var marker = leaflet.circleMarker([39, -105], { radius: 8, weight: 1, color: "#274FCA", fillOpacity: 1 })
.addTo(map)
.bindPopup(this.id + '<br/>' + this.status + '<br/>');
marker.on('click', (e) => {
var popup = e.target.getPopup();
var div = L.DomUtil.create('div', 'command');
div.innerHTML = 'marker.id' + '<br/>' + 'marker.status' + '<br/>' + 'result.description' + '<br/><a id = "command">More Details</a> <br/>';
popup.setContent(div);
leaflet.DomEvent.addListener(div, 'click', () => {
this.navCtrl.push(Constants.Page.IssueDetails, { markerId: marker.id }, Constants.Animation['TransitionForward']);
});
});

Related

FileManagerBundle. Implement FileMangerBundle (artgris) using TinyMCE v6.2 with Symfony4

I have tinyMCE 6.2 in my project. How to chose file?
And I can't choose an image by click or by check.
The selected file path (tinymceCallBackURL) is empty. Can you help me?
tinyMCE init:
tinymce.init({ selector: '.tinymce', file_picker_callback: myFileBrowser, .......... }
My code js:
var type = meta.filetype;
var cmsURL = "file_manager/?conf=tiny";
if (cmsURL.indexOf("?") < 0) {
cmsURL = cmsURL + "?type=" + type;
} else {
cmsURL = cmsURL + "&type=" + type;
}
var windowManagerCSS = '<style type="text/css">' + '.tox-dialog {max-width: 100%!important; width:97.5%!important; overflow: hidden; height:95%!important; border-radius:0.25em;}' + '.tox-dialog__body { padding: 0!important; }' + '.tox-dialog__body-content > div { height: 100%; overflow:hidden}' + '</style> ';
window.tinymceCallBackURL = '';
window.tinymceWindowManager = tinymce.activeEditor.windowManager;
tinymceWindowManager.open({
title: 'Menedżer plików',
url: cmsURL,
body: {
type: 'panel',
items: [{
type: 'htmlpanel',
html: windowManagerCSS + <iframe src="/file_manager/?conf=tiny&type=${type}" style="width:100%; height:500px" id="filemanager"></iframe> }]
},
buttons: [],
onClose: function () {
if (tinymceCallBackURL != '') callback(tinymceCallBackURL, {}); //to set selected file path } }); }````
I have a solution. (unswer in github issue https://github.com/artgris/FileManagerBundle/issues/107):
I needed to add module=tiny in cmsURL :
var cmsURL = "file_manager/?module=tiny&conf=tiny";
and replace:
html: windowManagerCSS + '<iframe src="/file_manager/?conf=tiny&type=${type}" ... thinking
with:
html: windowManagerCSS + '<iframe src="' + cmsURL ...
https://github.com/artgris/FileManagerBundle/blob/master/Resources/doc/tutorials/integrate-tinymce.md

How to stop cursor flickering over mapbox marker icons?

How do I stop cursor flickering over my Mapbox icons? Here is the live site where you can see the problem when hovering over the marker icons: https://rustic-waters-group.thesparksite.com/lakes/
Here is my code:
mapboxgl.accessToken = 'pk.eyJ1IjoiZG1pdHJpbWFydGluIiwiYSI6ImNreHRobHRmcjVqM3cydmt5NWkxdWNibTcifQ.CuN5Dwc963TW-BKRcowxBA';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/dmitrimartin/ckxtj5aur4fvv15mrhmihala8',
center: [-89.2, 44.33],
zoom: 9.2
});
map.on('load', () => {
const popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('mouseenter', 'lakes', (event) => {
map.getCanvas().style.cursor = 'pointer';
const features = map.queryRenderedFeatures(event.point, {
layers: ['lakes']
});
if (event.features.length === 0) return;
popup.setLngLat(features[0].geometry.coordinates);
popup.setHTML('<h3 class="lake-popup">' + features[0].properties.title + '</h3>');
popup.setMaxWidth("calc(100vw - 40px);");
popup.addTo(map);
});
map.on('mouseleave', 'lakes', () => {
map.getCanvas().style.cursor = '';
popup.remove();
});
map.on('click', 'lakes', (event) => {
const features = map.queryRenderedFeatures(event.point, {
layers: ['lakes']
});
if (event.features.length === 0) return;
window.location.href = ('/lakes/' + features[0].properties.url + '/');
});
document.getElementById("lakes-header").onmouseover = function() {
MyMouseOver();
};
function MyMouseOver() {
document.getElementById("wrapper").style.display = "none";
document.getElementById("lakes-header").style.display = "none";
}
});
The issue stems from the popup box on top of the layer and can be fixed by adding the CSS property 'cursor-events: none' to the popup. That should stop the flickering and shouldn't interfere with the layers.

This.localStream is null

I'm trying to develop and application that allow to a medic and a patient be able to communicate using an Api called connectycube, the chat and video call work, the problem is with to mute sound and video. I have implemented the buttons to mute sound and video, all this using jQuery dialogs, the first time I mute audio or video works, but when I close the dialog finishing the session and then I open the dialog with a new session, to mute audio and video do not work anymore and the message in the console is This.localStream is null
My Source Code:
const CREDENTIALS = {
appId: 'xxxxx',
authKey: 'xxxxx',
authSecret: 'xxxxx'
};
ConnectyCube.init(CREDENTIALS);
//This is a button in a main jquery dialog, this is the beginning of all
{
text: 'VideoCall',
click: function () {
$('#dv_progess').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.createSession().then((session) => {
$('#dv_progess').dialog('close');
signup_user();
$('#dv_videocall').dialog('option', 'position', {my: 'right top', at: 'right top', of: window}).dialog('open');
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progess').dialog('close');
$('#dv_message').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}
},
function signup_user() {
var login = 'P' + $('#hd_idusr').val();
/*Buscar si existe usuario registrado en la API*/
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.users.get({login: login}).then((result) => {
console.log('User Exists:' + result.user.id);
$('#dv_progress').dialog('close');
chat();
}).catch((error) => {
$('#dv_progress').dialog('close');
console.log('User not exists [' + error.info.message + ']');
var password = $('#txt_birthdate').val().replace(/-/g, '') + '*';
var email = $('#hd_email').val();
email = email ? email : login + '#email.com';
const userProfile = {
login: login,
password: password,
full_name: $('#txt_names').val(),
email: email
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.users.signup(userProfile).then((data) => {
console.log('ok=>' + data.user.id);
$('#dv_progress').dialog('close');
chat();
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
});
}
function chat() {
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
var login_patient = 'P' + $('#hd_idusr').val();
ConnectyCube.users.get({login: login_patient}).then((result) => {
$('#dv_progress').dialog('close');
var id_patient = result.user.id;
$('#hd_idpatient').val(id_patient);
const userCredentials = {
login: 'S' + $('#txt_medic').attr('data-id-user'),
password: $('#txt_medic').attr('data-psw')
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.createSession(userCredentials).then((session) => {
$('#dv_progress').dialog('close');
console.log(JSON.stringify(session));
console.log('Medic Created session');
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.login(userCredentials).then((user) => {
var id_professional = user.id;
console.log('Medic login succesful=>' + id_professional);
$('#hd_idprofessional').val(id_professional);
const chatCredentials = {
userId: id_professional,
password: $('#txt_medic').attr('data-psw')
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.chat.connect(chatCredentials).then(() => {
$('#dv_progress').dialog('close');
console.log('Medic Connected to chat');
console.log('Id Paciente:' + id_patient);
const dialogParams = {
type: 3,
occupants_ids: [id_patient]
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.chat.dialog.create(dialogParams).then(dialog => {
$('#dv_progress').dialog('close');
console.log(JSON.stringify(dialog));
console.log('Dialog Created:' + dialog._id);
$('#hd_iddialog').val(dialog._id);
$('#dv_messagearea').prop('contenteditable', true);
$('#btn_sendmsg,#btn_startvideocall,#btn_finishvideocall').prop('disabled', false);
}).catch(error => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error:' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error:' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error:' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error:' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
/*Fin Login Medico*/
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}
function onMessage(userId, message) {
console.log('[ConnectyCube.chat.onMessageListener] callback:', userId, message);
var dv_message = $('#dv_messageschat');
dv_message.append('<div><b>Patient:</b>' + message.body + '</div>');
dv_message.scrollTop(dv_message[0].scrollHeight);
}
function isTyPing(isTyping, userId, dialogId) {
console.log("[ConnectyCube.chat.onMessageTypingListener] callback:", isTyping, userId, dialogId);
}
function sendMessage() {
ConnectyCube.chat.sendIsStopTypingStatus($('#hd_idpatient').val());
var mensaje = $('#dv_messagearea').text();
const message = {
type: 'chat',
body: mensaje,
extension: {
save_to_history: 1,
dialog_id: $('#hd_iddialog').val()
},
markable: 1
};
message.id = ConnectyCube.chat.send($('#hd_idpatient').val(), message);
var dv_message = $('#dv_messageschat');
dv_message.append('<div><b>Yo:</b>' + mensaje + '</div>');
dv_message.scrollTop(dv_message[0].scrollHeight);
$('#dv_messagearea').html('');
}
$('#dv_messagearea').keypress(function (e) {
ConnectyCube.chat.sendIsTypingStatus($('#hd_idpatient').val());
setTimeout(function () {
ConnectyCube.chat.sendIsStopTypingStatus($('#hd_idpatient').val());
}, 1000);
if (e.keyCode == 13) {
sendMessage();
return false;
}
});
function startVideo() {
const calleesIds = [$('#hd_idprofessional').val(), $('#hd_idpatient').val()]; /*User's ids*/
const sessionType = ConnectyCube.videochat.CallType.VIDEO;
const additionalOptions = {};
const session = ConnectyCube.videochat.createNewSession(calleesIds, sessionType, additionalOptions);
const mediaParams = {
audio: true,
video: true,
options: {
muted: true,
mirror: true
}
};
session.getUserMedia(mediaParams).then((localStream) => {
console.log(JSON.stringify(localStream));
session.attachMediaStream('vd_video1', localStream);
/*Iniciar la llamada*/
const extension = {};
session.call(extension, (error) => {
console.log(JSON.stringify(error));
});
$('#btn_finishvideocall').on('click', {x: session}, finishCall);
}).catch((error) => {
console.log(JSON.stringify(error));
});
}
function finishCall(e) {
const extension = {};
e.data.x.stop(extension);
/*Clean local stream*/
var videoElem1 = document.getElementById('vd_video1'),
stream1 = videoElem1.srcObject;
if (stream1 != null) {
var tracks = stream1.getTracks();
tracks.forEach(function (track) {
track.stop();
});
videoElem1.srcObject = null;
}
/*Clean remote stream*/
var videoElem2 = document.getElementById('vd_video2'),
stream2 = videoElem2.srcObject;
if (stream2 != null) {
var tracks = stream2.getTracks();
tracks.forEach(function (track) {
track.stop();
});
videoElem2.srcObject = null;
}
}
$('#dv_controllsvideocall').find('button').prop('disabled', true);
$('#btn_mutesound,#btn_mutevideo').hide();
function setSound(e) {
const session = e.data.x;
if (e.data.y == 'mute') {
$('#btn_mutesound').show();
$('#btn_unmutesound').hide();
session.mute('audio');
console.log('muted audio');
} else {
$('#btn_mutesound').hide();
$('#btn_unmutesound').show();
session.unmute('audio');
console.log('unmuted audio');
}
}
function setVideo(e) {
const session = e.data.x;
if (e.data.y == 'mute') {
$('#btn_mutevideo').show();
$('#btn_unmutevideo').hide();
session.mute('video');
console.log('muted video');
} else {
$('#btn_mutevideo').hide();
$('#btn_unmutevideo').show();
session.unmute('video');
console.log('unmuted video');
}
}
function acceptedCall(session, userId, extension) {
console.log('Accepted call');
$('#dv_controllsvideocall').find('button').prop('disabled', false);
}
function setStream(session, userID, remoteStream) {
console.log('stream assigned');
session.attachMediaStream('vd_video2', remoteStream);
$('#btn_mutesound').on('click', {x: session, y: 'unmute'}, setSound);
$('#btn_unmutesound').on('click', {x: session, y: 'mute'}, setSound);
$('#btn_mutevideo').on('click', {x: session, y: 'unmute'}, setVideo);
$('#btn_unmutevideo').on('click', {x: session, y: 'mute'}, setVideo);
}
function onStopCall(session, userId, extension) {
console.log('Finished Call');
}
ConnectyCube.chat.onMessageListener = onMessage;
ConnectyCube.chat.onMessageTypingListener = isTyPing;
ConnectyCube.videochat.onAcceptCallListener = acceptedCall;
ConnectyCube.videochat.onRemoteStreamListener = setStream;
ConnectyCube.videochat.onStopCallListener = onStopCall;
$('#btn_sendmsg').click(function () {
sendMessage();
});
$('#btn_startvideocall').click(function () {
startVideo();
});
$('#btn_exitvideocall').click(function () {
$('#dv_videocall').dialog('close');
});
/*Dialog for video call*/
$('#dv_videocall').dialog({
autoOpen: false,
resizable: false,
height: 600,
width: 220,
modal: false,
close: function () {
$(this).find('input').val('');
$('#dv_messagearea').prop('contenteditable', false).html('');
$('#dv_messageschat').html('');
$('#btn_sendmsg,#btn_startvideocall,#btn_finishvideocall').prop('disabled', true);
$('#dv_controllsvideocall').find('button').prop('disabled', true);
if (ConnectyCube.chat.isConnected) {
$('#btn_finishvideocall').trigger('click');
ConnectyCube.chat.disconnect();
ConnectyCube.logout().catch((error) => {
console.log('logout=>' + JSON.stringify(error));
});
ConnectyCube.destroySession().catch((error) => {
console.log('destroySession=>' + JSON.stringify(error));
});
}
}
});
$(window).bind('beforeunload', function () {
if (ConnectyCube.chat.isConnected) {
$('#btn_finishvideocall').trigger('click');
ConnectyCube.chat.disconnect();
ConnectyCube.logout().catch((error) => {
console.log('logout=>' + JSON.stringify(error));
});
ConnectyCube.destroySession().catch((error) => {
console.log('destroySession=>' + JSON.stringify(error));
});
}
});
I think the problem is in the function finishCall() when I clean the video tag and I don't know if that is the right way to free the resources. Despite this the chat and video call still work.
If someone has experience please help me, becasue I didn't found any solution, thanks in advance.

Famo.us drag & drop surfaces?

I've gone through the handy Famo.us University tutorials and am prototyping a drag & drop interface. It's the typical UI where the user can drag an icon and drop it onto a target to do something. I've gotten the drag part down, but detecting the drop is getting very hairy. Is there built-in collision detection in Famo.us?
Edit: I've looked at the Collision API but it's not clear whether this would work across views.
Here's how I've organized the project:
AppView (overall container)
|
|__ MenuView (sidebar) --> VizView (icons in MenuView)
|
|__ PageView (workspace where the drop targets live)
This may not be the best way to go about this. I'm not sure. Hooking up input events across the views seems to be painful.
VizView source:
/*** VizView.js ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var Modifier = require('famous/core/Modifier');
var ImageSurface = require('famous/surfaces/ImageSurface');
var Transitionable = require("famous/transitions/Transitionable");
var SnapTransition = require("famous/transitions/SnapTransition");
Transitionable.registerMethod("spring", SnapTransition);
var GenericSync = require('famous/inputs/GenericSync');
var MouseSync = require('famous/inputs/MouseSync');
var TouchSync = require('famous/inputs/TouchSync');
GenericSync.register({'mouse': MouseSync, 'touch': TouchSync});
function VizView() {
View.apply(this, arguments);
_createIcon.call(this);
}
VizView.prototype = Object.create(View.prototype);
VizView.prototype.constructor = VizView;
VizView.DEFAULT_OPTIONS = {
width: 200,
height: 100,
angle: -0.2,
iconSize: 98,
iconUrl: '',
title: 'Empty',
fontSize: 26
};
function _createIcon() {
this.zIndex = 0;
var me = this;
var iconSurface = new ImageSurface({
size: [this.options.iconSize, this.options.iconSize],
content : this.options.iconUrl,
properties: {
cursor: 'pointer'
}
});
var initModifier = new Modifier({
// places the icon in the proper location
transform: Transform.translate(24, 2, 0)
});
this.position = new Transitionable([0, 0]);
var positionModifier = new Modifier({
transform : function(){
var currentPosition = me.position.get();
return Transform.translate(currentPosition[0], currentPosition[1], me.zIndex);
},
});
var sync = new GenericSync(
['mouse', 'touch']
);
sync.on('start', function(data){
me.zIndex = 1;
});
sync.on('update', function(data){
me.updateIcon(data);
});
sync.on('end', function(data){
var velocity = data.velocity;
me.position.set([0, 0], {
method : 'spring',
period : 150,
velocity : velocity
});
me.zIndex = 0;
});
iconSurface.pipe(sync);
this.add(positionModifier).add(initModifier).add(iconSurface);
this.updateIcon = function (data) {
if (this.zIndex == 0) return;
var currentPosition = this.position.get();
this.position.set([
currentPosition[0] + data.delta[0],
currentPosition[1] + data.delta[1]
]);
}
}
module.exports = VizView;
});
A VizView is instantiated in MenuView as such:
var vizView = new VizView({
iconUrl: "path/to/iconUrl",
title: "Viz Title"
});
var vizModifier = new StateModifier({
transform: Transform.translate(0, yOffset, 0)
});
this.add(vizModifier).add(vizView);
A draggable Surface in Famo.us is not really a DOM draggable element although it can be setup to work in a browser using the mouse. I have not been able to get GenericSync and touch to work with this solution yet.
Reading the pitfalls on the Famo.us site, there are hints to drag and drop with surface draggables being an issue.
How do I find the absolute position of a Surface on the screen?
By design this is not possible. It is something the developer should
not care about. For the time being, this means that interactions such
as drag and drop are harder to implement, but this is intended and we
are working on an elegant solution for these use-cases.
Although: When not using GenericSync, you can use the DOM draggable events with a Famo.us Surface as you stated in the comments and link to the John Traver solution.
But: This solution will not work on mobile touch devices using Famo.us at the time of this answer. Getting this to work with touch may prove to be more difficult as stated in the pitfalls. Let's hope this gets solved in versions following 0.3.5 or in MixedMode (WebGL and DOM)
define('main', function(require, exports, module) {
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var ImageSurface = require('famous/surfaces/ImageSurface');
var Transform = require('famous/core/Transform');
var Modifier = require('famous/core/Modifier');
var StateModifier = require('famous/modifiers/StateModifier');
var Draggable = require('famous/modifiers/Draggable');
var TransitionableTransform = require('famous/transitions/TransitionableTransform');
var mainContext = Engine.createContext();
var transTransform = new TransitionableTransform();
transTransform.set(Transform.translate(100, 0, 0));
var captureSurface = new Surface({
content: 'Drag to Here',
size: [300, 300],
properties: {
textAlign: 'center',
lineHeight: '300px',
backgroundColor: 'rgba(255,255,0,0.4)',
cursor: 'pointer'
},
attributes: {
dropzone: 'copy file:image/png file:image/gif file:image/jpeg'
}
});
captureSurface.on('dragenter', function(evt) {
console.log('dragenter', evt);
evt.preventDefault();
return false;
});
captureSurface.on('dragleave', function(evt) {
console.log('dragleave', evt);
captureSurface.setProperties({
border: 'none'
});
evt.preventDefault();
return false;
});
captureSurface.on('dragover', function(evt) {
console.log('dragover', evt);
captureSurface.setProperties({
border: '4px dashed black'
});
evt.preventDefault();
return false;
});
captureSurface.on('drop', function(evt) {
console.log('drop', evt);
evt.preventDefault();
evt.stopPropagation();
captureSurface.setProperties({
border: '4px solid red'
});
files = evt.dataTransfer.files;
console.log(files);
});
mainContext.add(new Modifier({
origin: [0.5, 0.5],
align: [0.5, 0.5]
})).add(captureSurface);
var surface = new Surface({
content: 'DOM Draggable',
size: [300, 100],
properties: {
backgroundColor: 'rgba(255,0,0,0.4)',
cursor: 'move'
},
attributes: {
draggable: 'true'
}
});
surface.on('drag', function(evt) {
console.log('surface drag', evt)
});
var imageSurface = new ImageSurface({
content: 'http://i.imgur.com/NGOwZeT.png',
size: [100, 100],
properties: {
cursor: 'copy'
},
attributes: {
draggable: 'true'
}
});
imageSurface.on('drag', function(evt) {
console.log('imageSurface drag', evt)
});
imageSurface.on('dragend', function(evt) {
console.log('imageSurface dragend', evt)
});
var dragSurface = new Surface({
content: 'Drag Me',
size: [100, 100],
properties: {
backgroundColor: 'rgba(0,0,0,0.1)',
cursor: 'move'
},
attributes: {
draggable: 'true'
}
});
dragSurface.on('dragstart', function(evt) {
console.log('dragSurface dragstart', event, evt);
});
dragSurface.on('drag', function(evt) {
console.log('dragSurface dragstart', event, evt);
});
var modifier = new Modifier({
origin: [0, 0],
align: [0, 0],
transform: transTransform
});
var imageModifier = new Modifier({
origin: [0, 0.5],
align: [0, 0.5]
});
var draggable = new Draggable();
draggable.subscribe(dragSurface);
mainContext.add(modifier).add(surface);
mainContext.add(imageModifier).add(imageSurface);
mainContext.add(draggable).add(dragSurface);
draggable.on('update', function(e) {
console.log('draggable update', e, event);
var pos = e.position;
surface.setContent('Draggable Position is ' + pos);
transTransform.set(Transform.translate(pos[0] + 100, pos[1], 0));
});
draggable.on('end', function(e) {
var pos = e.position;
surface.setContent('Draggable End Position is ' + pos);
transTransform.set(Transform.translate(pos[0] + 100, pos[1], 0));
});
//draggable.deactivate();
});
require(['main']);
<script src="http://requirejs.org/docs/release/2.1.16/minified/require.js"></script>
<script src="http://code.famo.us/lib/requestAnimationFrame.js"></script>
<script src="http://code.famo.us/lib/classList.js"></script>
<script src="http://code.famo.us/lib/functionPrototypeBind.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.famo.us/famous/0.3.5/famous.css" />
<script src="http://code.famo.us/famous/0.3.5/famous.min.js"></script>

Extjs 4.0 MVC Add components to a form based on Store

I am ashamed to say I have spent most of today on this. I am trying to build a form based on the contents of an data store. I am using Ext.js and the MVC architecture. Here's what I have:
var myitems = Ext.create('Ext.data.Store', {
fields: ['name', 'prompt', 'type'],
data :
[
{"name":"name", "prompt":"Your name" , "type":"textfield"},
{"name":"addr", "prompt":"Your street address", "type":"textfield"},
{"name":"city", "prompt":"Your city" , "type":"textfield"}
]
});
function genwidget(name, prompt, type)
{
console.log("In genwidget with name=" + name + ", prompt=" + prompt + ", type=" + type + ".");
var widget = null;
if (type == "textfield")
{
// widget = Ext.create('Ext.form.field.Text',
widget = Ext.create('Ext.form.TextField',
{
xtype : 'textfield',
name : name,
fieldLabel: prompt,
labelWidth: 150,
width : 400, // includes labelWidth
allowBlank: false
});
}
else
{
// will code others later
console.log("Unrecongized type [" + type + '] in function mywidget');
}
return widget;
};
function genItems(myitems)
{
console.log("Begin genItems.");
var items = new Ext.util.MixedCollection();
var howMany = myitems.count();
console.log("There are " + howMany + " items.");
for (var i = 0; i < myitems.count(); i++)
{
var name = myitems.getAt(i).get('name');
var prompt = myitems.getAt(i).get('prompt');
var type = myitems.getAt(i).get('type');
var widget = genwidget(name, prompt, type) ;
items.add(widget);
console.log("items.toString(): " + items.toString());
}
return items;
};
Ext.define('MyApp.view.dynamicform.Form' ,{
extend: 'Ext.form.Panel',
alias : 'widget.dynamicformform',
// no store
title: 'Dynamic Form',
id: 'dynamicform.Form',
bodyPadding: 5,
autoScroll: true,
layout: 'auto',
defaults:
{
anchor: '100%'
},
dockedItems: [ ],
items: genItems(myitems),
// Reset and Submit buttons
buttons: [
{
text: 'Reset',
handler: function()
{
this.up('form').getForm().reset();
console.log('Reset not coded yet');
}
},
{
text: 'Submit',
formBind: true, //only enabled once the form is valid
disabled: true,
handler: function()
{
var form = this.up('form').getForm();
if (form.isValid())
{
form.submit({
success: function(form, action)
{
console.log('Success not coded yet');
}
});
}
}
} // end submit
], // end buttons
initComponent: function()
{
console.log("--> in dynamicform init");
this.callParent(arguments);
console.log("--> leaving dynamicform init");
}
}); // Ext.define
The error I am getting (I've had many throughout the day) is "my.items.push is not a function".
Thanks in advance for any help you can offer!
items is expected to be an array not MixedCollection. It is changed to MixedCollection later on if I remember good. So to fix your issue change:
var items = new Ext.util.MixedCollection();
// ...
items.add(widget);
to
var items = [];
// ...
items.push(widget);
Consider as well defining items of form as an empty array and then in initComponent make use of Ext.apply:
var me = this,
items = genItems(myitems);
Ext.apply(me, {
items:items
});