I am trying to bind to a date using breeze and knockout. The data returned from the BreezeController is as expected. But I see this in the debugger:
TripDate: function dependentObservable() {
__ko_proto__: function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
_latestValue: Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)
__proto__: Invalid Date
The json data coming in back from the database server is:
TripDate: "2013-07-21T00:00:00.000"
Any idea why the date is "Invalid"?
use this in view model
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
//update the control when the view model changes
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).datepicker("setDate", value);
}
};
then in html
data-bind="datepicker:tripDate"
Now you will get what u need ....also you can save the updated date
check it if you just want to display
ko.bindingHandlers.dateString = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(),
allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var pattern = allBindings.datePattern || 'MM/dd/yyyy';
$(element).text(valueUnwrapped.toString(pattern));
}
}
in html replace 'datepicker' with 'dateString'
Related
I'm not able to reset the PlanningCalendar back to the initial startDate.
So, after clicking on Today or the Navigate Back or Foreward arrows there is no way of getting back to the initial start date.
I'm not sure if I'm doing it right, but you can find a working example here
Here is the controller
sap.ui.define(
[
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel',
'sap/ui/model/resource/ResourceModel',
'sap/m/MessageToast'
],
function (Controller, JSONModel, ResourceModel, MessageToast) {
'use strict';
var PageController = Controller.extend('view.Main', {
onInit: function () {
var oModel = new JSONModel();
oModel.setData({...});
var oView = this.getView();
oView.setModel(oModel);
},
dateFormatter: function (sDate) {
return new Date(sDate);
},
resetStartDate: function () {
var oView = this.getView();
var oPlanningCalendar = oView.byId('PC1');
var startDate = oPlanningCalendar.getStartDate();
oPlanningCalendar.setStartDate(startDate);
MessageToast.show("'resetStartDate' event fired.");
},
handleStartDateChange: function (oEvent) {
var oView = this.getView();
var oPlanningCalendar = oView.byId('PC1');
var startDate = oPlanningCalendar.getStartDate();
MessageToast.show("'startDateChange' event fired.\n\nNew start date is " + startDate.toString());
}
});
return PageController;
}
);
the problem is the following two lines of code.
var startDate = oPlanningCalendar.getStartDate();
oPlanningCalendar.setStartDate(startDate);
You get the date from current Planning Calendar, and then set the date back to it.
That means you do nothing.
Maybe you need to get the start date on initial of Planning Calendar. Not at the time you want to do the reset.
I have created view model
var catalog = ko.observableArray();
$.ajax({
type: "GET",
url: "http://localhost:8080/ticket-service/rest/ticket/list",
success: function(msg) {
catalog.push.apply(catalog, $.map(msg, function(data) {
return new Ticket(data)
}));
return catalog;
},
error: function(msg) {
console.log(msg)
}
});
and the model
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
this.ticketNo = ko.observable(data.ticketNo);
this.ticketTitle = ko.observable(data.ticketTitle);
this.longDescription = ko.observable(data.longDescription);
this.createdBy = ko.observable(data.createdBy);
this.createdOn= ko.observable(data.createdOn);
this.assignTo = ko.observable(data.assignTo);
this.priority = ko.observable(data.priority);
this.dueDate = ko.observable(data.dueDate);
this.status = ko.observable(data.status);
this.projectId = ko.observable(data.projectId);
}
with at the end viewmodel like this
return {
ticket: newTicket,
searchTerm: searchTerm,
catalog: filteredCatalog,
newTicket: newTicket,
addTicket: addTicket,
delTicket: delTicket
};
})();
console.log(vm);
ko.applyBindings(vm);
produce list,add, and delete form.The question is how can i use knockout mapping that can list from get methode.
you need to do something like this
Demonstrated taking a single entity from your code .
view:
Output Preview :
<pre data-bind="text:ko.toJSON($data,null,2)"></pre>
viewModel:
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
}
var mapping = {
create: function (options) {
return new Ticket(options.data);
}
};
var ViewModel = function () {
var self = this;
self.catalog = ko.observableArray();
var data = [{
'ticketId': 1
}, {
'ticketId': 2
}]
//under ajax call do the same but pass 'msg' in place of data
self.catalog(ko.mapping.fromJS(data, mapping)())
console.log(self.catalog()); // check console for output
};
ko.applyBindings(new ViewModel());
sample working fiddle here
Let's say we have a Join table vehicle_inspections and another join table inspection_actions, as well as basic tables for actions, vehicles, andinspections`.
Lets say I desire the following DB entries:
vehicles
----------------------------
id make
----------------------------
1 Toyota
actions
-------------------------------
id description
-------------------------------
2 Check Tire Pressue
inspections
-------------------------------
id location date
-------------------------------
3 New York tomorrow
vehicle_inspections
--------------------------------
vehicle_id inspection_id
--------------------------------
1 3
inspection_actions
--------------------------------
inspection_id action_id
--------------------------------
3 2
and the following bookshelf classes
inspection_actions.js
(function () {
'use strict';
var Repository = require('../repository');
module.exports = Repository.Model.extend({
tableName: 'inspection_actions',
});
})();
vehicle_inspections.js
(function () {
'use strict';
var Repository = require('../repository');
module.exports = Repository.Model.extend({
tableName = 'vehicle_inspections',
inspection: function () {
return this.belongsTo(require('inspection'));
},
fetchOrCreate: function(vehicleId, inspectionId, options) {
var self = this;
return self.query(function (qb) {
qb.where({
vehicle_id: vehicleId,
inspection_id: inspectionId
});
)}.fetch(options || {}).then(function (model) {
if (!model) {
model.save({
vehicle_id: vehicleId,
inspection_id: inspectionId
});
return model;
};
}
};
});
inspection.js
...
module.exports = Repository.Model.extend(_.extend({
tableName: 'inspections',
actions: function () {
return this.hasMany(require('./inspection-action'));
}
}));
And a route:
new VehicleInspection().fetchOrCreate(req.params.vehicle_id, req.params.inspection_id, {withRelated: ['inspection.actions']})
.then(function (vehicleInspection) {
var inspection = vehicleInspection.related('inspection');
console.log( inspection);
console.log(inspection.related(actions);
})
The inspection console log prints out the correct inspection, however, irrelevantly of what is in the database the second console.log prints out an empty result
{ length: 0,
models: [],
_byId: {},
...
targetIdAttribute: 'id',
foreignKey: undefined,
parentId: undefined,
parentTableName: 'tasks',
parentIdAttribute: 'id',
parentFk: undefined } }
This "bad" behaviour only occurs the first time a projectTasks entry is being created. What appears to be happening is that the inspection_action table is not being populated through the nested withRelated. How could I get this working nested create working?
I'm not completely clear what you are trying to achieve, but here is how I would generally set things up. First I'd create a base model (assuming its saved as base.js), I think you are going to have some problems with circular dependencies, so using the Bookshelf registry plugin would be good:
var config = {
client: // whatever client you are using,
connection: // url to your database
};
var db = require('knex')(config);
var Bookshelf = require('bookshelf')(db);
var Base = Bookshelf.Model.extend({
// Put anything here that will be helpful for your use case
});
Bookshelf.plugin('registry');
Base.model = Bookshelf.model.bind(Bookshelf);
module.exports = Base;
Next create your Vehicle model:
require('inspection');
require('action');
var Base = require('base');
var Vehicle = Base.Model.extend({
tableName = 'vehicles',
inspections: function () {
return this.belongsToMany('Inspection',
'inspections_vehicles', 'vehicle_id', 'inspection_id');
},
actions: function() {
return this.belongsToMany('Action',
'actions_vehicles', 'vehicle_id', 'action_id');
}
};
module.exports = Base.model('Vehicle', Vehicle);
Then an inspection model:
require('vehicle');
var Base = require('base');
var Inspection = Base.Model.extend({
tableName = 'inspection',
vehicles: function () {
return this.belongsToMany('Vehicle',
'inspections_vehicles', 'inspection_id', 'vehicle_id');
}
};
module.exports = Base.model('Inspection', Inspection);
Finally an action model:
var Base = require('base');
var Action = Base.Model.extend({
tableName = 'actions',
};
module.exports = Base.model('Action', Action);
Now assuming that the database isn't already filled in with the data you supplied, we can populate it:
var Inspection = require('inspection');
var Vehicle = require('vehicle');
var Action = require('action');
var toyota;
var newYorkInspection
Vehicle.forge().save({name: 'Toyota'})
.then(function(vehicle) {
toyota = vehicle;
return Inspection.forge().save({location: 'New York', date: 'Tomorrow'});
}).then(function(inspection){
newYorkInspection = inspection;
return toyota.inspections().attach(newYorkInspection);
}).then(function() {
return Action.forge().save({description: 'Check Tire Pressure'});
}).then(function(tirePressureAction) {
return toyota.actions().attach(tirePressureAction);
});
Now I can fetch the toyota vehicle with the related actions and inspections:
var Vehicle = require('vehicle');
return Vehicle.forge({'name': 'Toyota'}).fetch({
withRelated: ['inspections', 'actions']
}).then(function(toyota){
var toyotaInspections = toyota.related('inspections');
var toyotaActions = toyota.related('actions');
});
I created a service called AppService.
Its function getUserPostionOptions is supposed to return an object:
getUserPostionOptions: function (user) {
// PositionOptions.findOne({id:'53f218deed17760200778cfe'}).exec(function (err, positionOptions) {
var positionDirectionsOptions = [1,2,3];
var positionLengthsOptions = [4,5,6];
var object = {
directions:positionDirectionsOptions,
lengths:positionLengthsOptions
};
return object;
// });
}
This works, in my controller positionOptions gets populated correctly:
var positionOptions = AppService.getUserPostionOptions(user);
However, when I uncomment the find query the item is found but the object returns undefined.
Thank in advance for your help
SailsJs ORM (and almost NodeJs database querying methods) uses non-blocking mechanism via callback function. So you have to change your code into:
getUserPostionOptions: function (user, callback) {
PositionOptions.findOne({id:'53f218deed17760200778cfe'}).exec(function (err, positionOptions) {
var positionDirectionsOptions = [1,2,3];
var positionLengthsOptions = [4,5,6];
var object = {
directions:positionDirectionsOptions,
lengths:positionLengthsOptions
};
callback(null, object); // null indicates that your method has no error
});
}
Then just use it:
AppService.getUserPostionOptions(user, function(err, options) {
if (!err) {
sails.log.info("Here is your received data:");
sails.log.info(options);
}
});
This is my code
/******************************************************/
import Ember from "ember";
var TodosController = Ember.ArrayController.extend({
actions: {
createTodo: function(){
// Get the todo title by the "New Todo" input
var title = this.get('newTitle');
if(!title.trim()){ return; }
// Create the new Todo model
var todo = this.store.createRecord('todo', {
title: title,
isCompleted: false
});
// Clear the 'New Todo' input field
this.set('newTitle', '');
// Save the new model
todo.save();
},
clearCompleted: function(){
var completed = this.filterBy('isCompleted', true);
completed.invoke('deleteRecord');
completed.invoke('save');
}
},
remaining: function() {
return this.filterBy('isCompleted', false).get('length');
}.property('#each.isCompleted'),
inflection: function() {
var remaining = this.get('remaining');
return remaining === 1 ? 'todo' : 'todos';
}.property('remaining'),
hasCompleted: function(){
return this.get('completed') > 0;
}.property('completed'),
completed: function(){
return this.filterBy('isCompleted', true).get('length');
}.property('#each.isCompleted'),
allAreDone: function(key, value) {
if(value === undefined){
return !!this.get('length') && this.everyProperty('isCompleted', true);
} else {
this.setEach('isCompleted', value);
this.invoke('save');
return value;
}
}.property('#each.isCompleted')
});
export default TodosController;
/*******************************************************/
In terminal not showing any error when i run this command
$ ember server
but in browser not showing any thing and console showing this error
Uncaught Error: Assertion Failed: ArrayProxy expects an Array or
Ember.ArrayProxy, but you passed object
Please suggest me what i m doing wrong, the code is also on github : https://github.com/narayand4/emberjs
thanks in advance.
The most likely reason for this is that you have a controller which extends from Ember.ArrayController while you only return a plain object in the corresponding model.
I had the same issue and changed my controller to extend Ember.Controller instead.
In the related route for this controller, your model method doesn't return an array, as you've indicated by extending an arrayController.