Weird Backbone.Validation bug when used with require.js and backbone.stickit - javascript

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;
});

Related

how to inherit models.js in pos and make some changes?

models_extend.js
odoo.define('pos_ticket.models_extend', function (require) {
"use strict";
var x = require('point_of_sale.models');
var models = pos_model.PosModel.prototype.models;
models.push(
{
model: 'res.company',
fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id', 'tax_calculation_rounding_method','city','trn_no'],
ids: function(self){ return [self.user.company_id[0]]; },
loaded: function(self,companies){ self.company = companies[0]; },
},
{
model: 'product.product',
fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'barcode', 'default_code',
'to_weight', 'uom_id', 'description_sale', 'description',
'product_tmpl_id','tracking','arb'],
order: ['sequence','default_code','name'],
domain: [['sale_ok','=',true],['available_in_pos','=',true]],
context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
loaded: function(self, products){
self.db.add_products(products);
},
},
{
model: 'product.product',
fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'barcode', 'default_code',
'to_weight', 'uom_id', 'description_sale', 'description',
'product_tmpl_id','tracking','arb'],
order: ['sequence','default_code','name'],
domain: [['sale_ok','=',true],['available_in_pos','=',true]],
context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
loaded: function(self, products){
self.db.add_products(products);
},
}
);
x.Order = x.Order.extend({
export_for_printing: function(){
var self = this;
this.pos = options.pos;
var company = this.pos.company;
var receipt = {
company:{
city:company.city,
trn_no:company.trn_no,
}
}
return receipt;
},
});
I want to add city and trn_no in res.company and arb in product.product to see the arabic translation.Then only i can submit my project in time, i am literally trapped please help me .i am a trainee .
To add new field in POS modules necessary in models.js override PosModel in the parent models which we take from “point_of_sale.models”.
After some changes
odoo.define('pos_ticket.models_extend', function (require) {
"use strict";
var x = require('point_of_sale.models');
var _super = x.PosModel.prototype;
module.PosModel = x.PosModel.extend({
initialize: function (session, attributes) {
// call super to set all properties
_super.initialize.apply(this, arguments);
// here i can access the models list like this and add an element.
this.models.push(
{
// load allowed users
model: 'res.company',
fields: ['city','trn_no'],
domain: function(self){ return [['id','in',self.users.company_id]]; },
loaded: function(self,companies){
console.log(companies);
self.allowed_users = companies;
}
},{
model: 'product.product',
fields: ['arb'],
order: ['sequence','default_code','name'],
domain: [['sale_ok','=',true],['available_in_pos','=',true]],
context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
loaded: function(self, products){
self.db.add_products(products);
}
},
)
return this;
}
});
});
now i need to inherit another function called "export_for_printing" and add those new fields in it so that i can print these fields.how?
Just add the modifications to the self.models array like this. This works for the version 8. Maybe it you need to adapt it:
if (typeof jQuery === 'undefined') { throw new Error('Product multi POS needs jQuery'); }
+function ($) {
'use strict';
openerp.your_module_name = function(instance, module) {
var PosModelParent = instance.point_of_sale.PosModel;
instance.point_of_sale.PosModel = instance.point_of_sale.PosModel.extend({
load_server_data: function(){
var self = this;
self.models.forEach(function(elem) {
if (elem.model == 'res.company') {
elem.fields = // make your new assignations here
elem.domain = // ...
elem.loaded = // ...
} else if (elem.model == 'product.product') {
// [...]
}
})
var loaded = PosModelParent.prototype.load_server_data.apply(this, arguments);
return loaded;
},
});
}
}(jQuery);

ko.validation.group not working

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

Meteor + polymer without blaze

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?

Backbone model attribute

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

Understanding more about Telerik Platform

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.

Categories

Resources