I have web-application in knockout.js javascript framework.
I have following model:
function ClientContactRepository() {
// View Model State
this.model = null;
// Return View Model
this.GetModel = function () {
this.model = {
ID: ko.observable(),
Title: ko.observable().extend({ required: true }),
FirstName: ko.validatedObservable().extend({ required: true }),
MI: ko.observable(),
LastName: ko.observable().extend({ required: true }),
SecurityTab: ko.validation.group([this.FirstName,this.LastName], { deep: true })
submit: function () {
alert(this.SecurityTab.length);
}
};
return this.model;
};
}
i am trying to group on FirstName and LastName inside SecurityTab, but on Save click event every time i am getting this.SecurityTab.length =0.
what can be reason ? why group is not working ?
Thanks
Related
I have experience in writing statics functions in moongose like
var mongoose =require('mongoose');
var Schema = mongoose.Schema;
var adminSchema = new Schema({
fullname : String,
number : Number,
email: String,
auth : {
username: String,
password : String,
salt: String
}
});
adminSchema.statics.usernameInUse = function (username, callback) {
this.findOne({ 'auth.username' : username }, function (err, doc) {
if (err) callback(err);
else if (doc) callback(null, true);
else callback(null, false);
});
};
here usernameInUse is the function I wana write but using sequelize for mysql database
my model
/*
This module is attendant_user table model.
It will store attendants accounts details.
*/
"use strict";
module.exports = function(sequelize, DataTypes) {
var AttendantUser = sequelize.define('AttendantUser', {
username : {
type : DataTypes.STRING,
allowNull : false,
validate : {
isAlpha : true
}
},{
freezeTableName : true,
paranoid : true
});
return AttendantUser;
};
How to add statics function here..??
Well, you can easily use Expansion of models
var User = sequelize.define('user', { firstname: Sequelize.STRING });
// Adding a class level method
User.classLevelMethod = function() {
return 'foo';
};
// Adding an instance level method
User.prototype.instanceLevelMethod = function() {
return 'bar';
};
OR in some cases you may use getter and setter on your models. See the docs:
A) Defining as part of a property:
var Employee = sequelize.define('employee', {
name: {
type : Sequelize.STRING,
allowNull: false,
get : function() {
var title = this.getDataValue('title');
// 'this' allows you to access attributes of the instance
return this.getDataValue('name') + ' (' + title + ')';
},
},
title: {
type : Sequelize.STRING,
allowNull: false,
set : function(val) {
this.setDataValue('title', val.toUpperCase());
}
}
});
Employee
.create({ name: 'John Doe', title: 'senior engineer' })
.then(function(employee) {
console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
console.log(employee.get('title')); // SENIOR ENGINEER
})
B) Defining as part of the model:
var Foo = sequelize.define('foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
getterMethods : {
fullName : function() { return this.firstname + ' ' + this.lastname }
},
setterMethods : {
fullName : function(value) {
var names = value.split(' ');
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
},
}
});
Hope it helps.
AttendantUser.usernameInUse = function (username, callback) {
...
};
return AttendantUser;
I'm trying to use meteor + polymer without blaze templating.
I make this behavior:
MeteorBehavior = {
properties: {
isReady: {
type: Boolean,
value: false,
notify: true
},
currentUser: {
type: Object,
value: null,
notify: true
}
},
ready: function () {
var self = this;
self.subscriptions.forEach(function(itm){
itm = $.type(itm) == 'array' ? itm : [itm];
itm[itm.length] = function () {
self.isReady = true;
};
Meteor.subscribe.apply(null, itm);
});
Meteor.startup(function () {
Tracker.autorun(function(){
self.currentUser = Meteor.user();
});
Tracker.autorun(self.autorun.bind(self));
});
},
subscriptions: [],
autorun: function() { }
};
And i use it:
(function () {
Polymer({
is: 'posts-list',
posts: [],
behaviors: [MeteorBehavior],
autorun: function(){
this.posts = Posts.find().fetch();
},
subscriptions: ['posts']
});
})();
Is it good solution? And how i can animate data changing without blaze uihooks?
I have a Backbone Model that basically looks like this:
var User = Backbone.Model.extend({
idAttribute: "_id",
givenName: 'UserModel',
urlRoot: '/users',
defaults: {
firstName: null,
lastName: null,
username: null,
password: null,
email: null
},
initialize: function (options) {
this.options = options || {};
_.bindAll(this, 'deleteModel', 'persist', 'validate');
},
constructor: function (attributes, options) {
Backbone.Model.apply(this, arguments);
},
validate: function (attr) {
return undefined;
},
persist: function (adds, callback) {
},
deleteModel: function (callback) {
}
});
but then why doesn't givenName show up in the debugger? I assume it's something to do with the nature of Backbone and nothing that's wrong with my code or the debugger.
here I even console.logged "model.givenName" and it is indeed defined. So I don't understand how Backbone is working:
https://www.dropbox.com/s/h61xpl8st98wcqi/Screenshot%202015-07-07%2020.57.49.png?dl=0
I amusing T. Hedersen's backbone.validation plugin (https://github.com/thedersen/backbone.validation) in conjunction with backbone.stickit plugin for model binding. I am running into a weird error where in it constantly validates all the fields when a single attribute of the model changes. Here is the code
Model
define(function(require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
Validation = require('backbone.validation'),
applicantModel = Backbone.Model.extend({
defaults: {
firstName: '',
middleName: '',
lastName: ''
},
initialize: function() {
},
validation: {
firstName: {
required: true
},
middleName: {
required: true
},
lastName: {
required: true
}
}
});
return new applicantModel;
});
View
define(function(require) {
"use strict";
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
tpl = require('text!templates/primaryApplicantInfo.html'),
lovValues = require('application/models/lovModel'),
Stickit = require('stickit'),
ApplicantModel = require('application/models/applicantModel'),
Validation = require('backbone.validation'),
template = _.template(tpl),
applicantView = Backbone.View.extend({
initialize: function() {
console.log('Inside the initialization function');
this.render();
},
bindings: {
'[name=firstName]': {
observe: 'firstName',
setOptions: {
validate: true
}
},
'[name=middleName]': {
observe: 'middleName',
setOptions: {
validate: true
}
},
'[name=lastName]': {
observe: 'lastName',
setOptions: {
validate: true
}
}
},
render: function() {
console.log("Inside applicant view");
//Render application header
this.$el.html(template);
this.stickit();
Backbone.Validation.bind(this, {
//The problem is here, this executes for all the attributes of the model when changing a single attribute
forceUpdate: true,
valid: function(view, attr) {
console.log("Validity is proper for "+attr);
},
invalid: function(view, attr, error) {
console.log("Validity is improper for "+attr);
}
});
$.each(lovValues.toJSON().suffix, function(val, text) {
console.log(text.text);
$('#applicantInfoSuffix').append(new Option(text.text, text.value));
});
Do not set the default values of the model as ''. Remove the default values if possible.
define(function(require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
Validation = require('backbone.validation'),
applicantModel = Backbone.Model.extend({
initialize: function() {
},
validation: {
firstName: {
required: true
},
middleName: {
required: true
},
lastName: {
required: true
}
}
});
return new applicantModel;
});
We are coming from .NET developers and trying to figure out this sample application Telerik Platform work utilizing Cordova (hybrid mode) especially for JavaScript.
The code is what we believe is Model for handling the activities. Is this correct? The syntax is a bit weird. It looks different from what we know. Can't figure out which one is method and which one is property.
It seems there is no more information about this type of Javascript. Where can I find more about this info beside Telerik site.
/**
* Activities view model
*/
var app = app || {};
app.Activities = (function () {
'use strict'
// Activities model
var activitiesModel = (function () {
var activityModel = {
id: 'Id',
fields: {
Text: {
field: 'Text',
defaultValue: ''
},
CreatedAt: {
field: 'CreatedAt',
defaultValue: new Date()
},
Picture: {
fields: 'Picture',
defaultValue: null
},
UserId: {
field: 'UserId',
defaultValue: null
},
Likes: {
field: 'Likes',
defaultValue: []
}
},
CreatedAtFormatted: function () {
return app.helper.formatDate(this.get('CreatedAt'));
},
PictureUrl: function () {
return app.helper.resolvePictureUrl(this.get('Picture'));
},
User: function () {
var userId = this.get('UserId');
var user = $.grep(app.Users.users(), function (e) {
return e.Id === userId;
})[0];
return user ? {
DisplayName: user.DisplayName,
PictureUrl: app.helper.resolveProfilePictureUrl(user.Picture)
} : {
DisplayName: 'Anonymous',
PictureUrl: app.helper.resolveProfilePictureUrl()
};
},
isVisible: function () {
var currentUserId = app.Users.currentUser.data.Id;
var userId = this.get('UserId');
return currentUserId === userId;
}
};
// Activities data source. The Backend Services dialect of the Kendo UI DataSource component
// supports filtering, sorting, paging, and CRUD operations.
var activitiesDataSource = new kendo.data.DataSource({
type: 'everlive',
schema: {
model: activityModel
},
transport: {
// Required by Backend Services
typeName: 'Activities'
},
change: function (e) {
if (e.items && e.items.length > 0) {
$('#no-activities-span').hide();
} else {
$('#no-activities-span').show();
}
},
sort: { field: 'CreatedAt', dir: 'desc' }
});
return {
activities: activitiesDataSource
};
}());
// Activities view model
var activitiesViewModel = (function () {
// Navigate to activityView When some activity is selected
var activitySelected = function (e) {
app.mobileApp.navigate('views/activityView.html?uid=' + e.data.uid);
};
// Navigate to app home
var navigateHome = function () {
app.mobileApp.navigate('#welcome');
};
// Logout user
var logout = function () {
app.helper.logout()
.then(navigateHome, function (err) {
app.showError(err.message);
navigateHome();
});
};
return {
activities: activitiesModel.activities,
activitySelected: activitySelected,
logout: logout
};
}());
return activitiesViewModel;
}());
Yes this are javascript objects. They seem a little different because they are being created using what is known as the Functional Pattern. One of its principles is to emulate private data as everything in javascript is declared in the global scope except whatever you declared inside a function, which creates a new scope hence it cannot be seen from the outside. You can google it or if your willing to document yourself i suggest you to read "Javascript: The Good Parts from Douglas Crockford" as it contains almost everything to be considered best practices for javascript these days.