How to manage newly created objects without "saving" before transitioning to a new route it in emberjs? - forms

I have an issue where I have a resource with a new route. When I transition to that new route I create a new object. On the form I have button to cancel, which removes that object. However, if I click a link on my navigation, say going back to the resource index, that object is there with whatever I put in the form. What's the best way of managing creating objects then moving away from the form?
My routes:
App.Router.map(function() {
this.resource('recipes', function() {
this.route('new');
this.route('show', { path: '/:recipe_id' });
});
this.resource('styles');
});
App.RecipesNewRoute = Ember.Route.extend({
model: function() {
return App.Recipe.createRecord({
title: '',
description: '',
instructions: ''
});
},
setupController: function(controller, model) {
controller.set('styles', App.Style.find());
controller.set('content', model);
}
});
My controller for the new route:
App.RecipesNewController = Ember.ObjectController.extend({
create: function() {
this.content.validate()
if(this.content.get('isValid')) {
this.transitionToRoute('recipes.show', this.content);
}
},
cancel: function() {
this.content.deleteRecord();
this.transitionToRoute('recipes.index');
},
buttonTitle: 'Add Recipe'
});
I'm using version 1.0.0.rc.1
Thanks!

Any code that you place in the deactivate method of your route will get executed every time you leave that route. The following code will delete the new model if the user hasn't explicitly saved it.
App.RecipesNewRoute = Ember.Route.extend({
// ...
deactivate: function() {
var controller = this.controllerFor('recipes.new');
var content = controller.get('content');
if (content && content.get('isNew') && !content.get('isSaving'))
content.deleteRecord();
},
// ...
});
As an added bonus, you now don't need to explicitly delete the record when the user presses the cancel button.

Related

How to re-run the ViewModel when you navigate between tabs in Oracle JET?

I am developing a CRUD app where i navigate from the page that display tables of my data to some forms to add or edit those data. i wanna, for example, when i add some data and navigate to the table page to show the new row added.
what i am using now is a refresh button that fetch again the data and insert it in the observable array.
here how i navigate to the tab when click submit:
$.ajax({
url: url +'/customer',
type: "POST",
data: JSON.stringify(dataObj),
contentType: 'application/json',
success: function (response) {
console.log(response);
},
error: function(error){
console.log("Something went wrong", error);
}
}).then(function () {
oj.Router.rootInstance.go("customers");
return true;
})
and this is the refresh action that i use now:
self.customerData = function (){
tempArray = [];
$.getJSON(url + "/customer").
then(function(tasks){
$.each(tasks, function (){
tempArray.push({
customerId: this._id,
name: this.name,
address: this.address,
email: this.email,
phone: this.phone,
area: this.area,
empNum: this.empNum,
sector: this.sector,
website: this.website,
facebook: this.facebook,
linkedin: this.linkedin,
activity: this.activity.name,
country: this.country.name
});
});
var auxTab =[];
for (var i =0; i<tempArray.length; i++)
{
var obj ={};
obj.customerId = i;
obj.name = tempArray[i].name;
obj.address = tempArray[i].address;
obj.email= tempArray[i].email;
obj.phone = tempArray[i].phone;
obj.area = tempArray[i].area;
obj.empNum = tempArray[i].empNum;
obj.website = tempArray[i].website;
obj.facebook = tempArray[i].facebook;
obj.linkedin = tempArray[i].linkedin;
obj.activity = tempArray[i].activity;
obj.country = tempArray[i].country;
if (tempArray[i].sector === 'true')
{
obj.sector = 'Public';
}
else
{
obj.sector = 'Private';
}
auxTab[i] = obj;
}
self.customerArray(auxTab);
});
};
self.refreshClick = function(event){
self.customerData();
return true;
}
i expect the row will be automatically shown when i navigate to the customer tab tab but it doesn't.
Why not simply call the customerData() method inside connected() function? This function is automatically invoked(if you have defined it) from the viewModel when a new html page is rendered.
Place this inside your ViewModel which has table data:
self.connected = function(){
self.customerData();
};
For more details, see the docs.
Note: The connected function is used in version 6 and beyond. Before that the function was called bindingsApplied.
In general you can use ko observables to ensure that new data is reflected in the UI. In case you are navigating to a VM, while creating the VM, you would pass parameters to it, which can contain observables. In that case when observable is updated, no matter from where, will reflect in your VM.
I see that your method fetching customer data is a simple array and I assume that it is bound to the UI. Did you try making the tempArray as an observable array?

How to access component model from outside

I have created a shell-in-shell construct in the index.html:
sap.ui.getCore().attachInit(function () {
// create a new Shell that contains the root view
var oShell = new sap.m.Shell({
id: "appShell",
app: new sap.ui.core.ComponentContainer({
name: "internal_app",
height: "100%"
})
});
// load the view that contains the unified shell
var oAppShellView = sap.ui.view({
type: sap.ui.core.mvc.ViewType.XML,
viewName: "internal_app.view.AppShell"
});
// access the unified shell from the view
var oUnifiedShell = oAppShellView.byId("unifiedShell");
// place the app shell in the unified shell
oUnifiedShell.addContent(oShell);
oAppShellView.placeAt("content");
});
In addition, a default model has been defined in manifest.json:
....
},
"models": {
"": {
"type": "sap.ui.model.json.JSONModel"
}
},
....
In the controller of the view internal_app.view.AppShell (which has been created by the code snippet above) I would now like to access the default model but neither this.getModel() nor this.getOwnerComponent().getModel() (getModel() and getOwnerComponent() return undefined) worked. I assume that the AppShell controller does not have an owner. But how can I access the default model in the onInit of that controller?
The app structure in your case is somewhat unusual - Nevertheless, you can always access the model, defined in manifest.json, as long as you can access the inner component.
Assuming this is referencing the controller of the internal_app.view.AppShell, you can get the default model like this:
onInit: function() {
var innerShell = sap.ui.getCore().byId("appShell"); // only if the app is standalone
this.componentLoaded(innerShell.getApp()).then(this.onComponentCreated.bind(this));
},
componentLoaded: function(componentContainer) {
var component = componentContainer.getComponent();
return component ? Promise.resolve(component) : new Promise(function(resolve) {
componentContainer.attachEventOnce("componentCreated", function(event) {
resolve(event.getParameter("component"));
}, this);
}.bind(this));
},
onComponentCreated: function(component) {
var myDefaultModel = component.getModel(); // model from manifest.json
// ...
}

kendo-ui autocomplete extend

I'm trying to extend the kendo-ui autocomplete control: I want the search start when te user hit enter, so basically I've to check the user input on keydown event.
I've tried to catch the keydown event with this code:
(function($) {
ui = kendo.ui,
Widget = ui.Widget
var ClienteText = ui.AutoComplete.extend({
init: function(element,options) {
var that=this;
ui.AutoComplete.fn.init.call(this, element, options);
$(this).bind('keydown',function(e){ console.log(1,e); });
$(element).bind('keydown',function(e){ console.log(2,e); });
},
options: {
[...list of my options...]
},
_keydown: function(e) {
console.log(3,e);
kendo.ui.AutoComplete.fn._keydown(e);
}
});
ui.plugin(ClienteText);
})(jQuery);
None of the binded events gets called, only the _keydown, and then I'm doing something wrong and cannot call the autocomplete "normal" keydown event.
I've seen a lot of examples that extend the base widget and then create a composite widget, but I'm not interested in doing that, I only want to add a functionality to an existing widget.
Can someone show me what I'm doing wrong?
Thank you!
What about avoiding the extend and take advantage of build in options and methods on the existing control : http://jsfiddle.net/vojtiik/Vttyq/1/
//create AutoComplete UI component
var complete = $("#countries").kendoAutoComplete({
dataSource: data,
filter: "startswith",
placeholder: "Select country...",
separator: ", ",
minLength: 50 // this is to be longer than your longest char
}).data("kendoAutoComplete");
$("#countries").keypress(function (e) {
if (e.which == 13) {
complete.options.minLength = 1; // allow search
complete.search($("#countries").val());
complete.options.minLength = 50; // stop the search again
}
});
This code actually work:
(function($) {
ui = kendo.ui,
ClienteText = ui.AutoComplete.extend({
init: function(element,options) {
ui.AutoComplete.fn.init.call(this, element, options);
$(element).bind('keydown',function(e){
var kcontrol=$(this).data('kendoClienteText');
if (e.which === 13) {
kcontrol.setDataSource(datasource_clientes);
kcontrol.search($(this).val());
} else {
kcontrol.setDataSource(null);
}
});
},
options: {
name: 'ClienteText',
}
});
ui.plugin(ClienteText);
})(jQuery);
but I don't know if it's the correct way to do it.

jqgrid display editform (the entire form) based on dataURL result

I am using form editing but I only want the ADD form to appear if the results from dataURL are correct. I can hide it, but I really don't want it at all on condition. Plus, the hide() only works after the alert is cleared
$("#schedule").jqGrid('editGridRow', "new", {
url: './ar_schedule_update.cgi?',
editData: {visitor:visitor},
beforeInitData: function() {
$('#schedule').setColProp('archiveid',{editable: true,hidden:false, edittype: 'select',
editoptions: {dataUrl: './ar_archiveid_edit_options.cgi?system=' + selected_system,
buildSelect: function(data) {
if (data.match(/^ERROR/)) {
$('#editmodschedule').hide(); //Makes it disappear ok after alert cleared
alert(data);
return false;
}
return data;
}
}
});
},
beforeShowForm: function(formid) {
//NEED TO EVALUATE CONDITION HERE? AND BAIL IF ERROR
},
onClose: function() {...............
Thanks in advance,
Mike

How do display a progress spinner in a Dojo FilteringSelect?

I have a Dojo FilteringSelect that takes about 20 seconds to load its values from the dB when the user clicks the arrow in the list box. I'd like to display a progress spinner while waiting for the data to be returned from the dB. Any ideas what event I would use to show my spinner when the data is being retrieved from the db and what event to hide the spinner when it completes? Thanks...
new FilteringSelect({
store: new dojo.data.ItemFileReadStore({ url: "some url here" }),
autocomplete: true,
maxHeight: "300",
required: false,
id: "country_select_id",
onChange: function(data) {
dojo.byId("case_info_status").innerHTML = " ";
}
}, "country_select_id");
I bet you could go a long way in the select._fetchHandle deferred and the store._fetchItems. Try this
var select = new .... Your FilteringSelect Construct( {} );
select._fetchHandle.addCallback(function() {
// success callback
dojo.style(dojo.byId('spinner'), "display", "none");
});
dojo.connect(select.store._fetchItems, function() {
if(select.store._loadFinished) return; // no-op
dojo.style(dojo.byId('spinner'), "display", "block");
});
EDIT:
select._fetchHandle will only be present briefly during the actual download (suppose we can hook onto it after select onOpen called). Instead, another private method in ItemFileReadStore comes in handy
dojo.connect(select.store._getItemsFromLoadedData, function() {
dojo.style(dojo.byId('spinner'), "display", "none");
});