Model is not a constructor-Backbone - javascript

I have created a model and collection for a json to be fetched as shown here.When i'm instantiating in the service i'm getting error that my model is not a constructor.My model uses collection of models for storing time/value pairs.
ServiceMonitoringModel.js
define(function(require) {
'use strict';
var _ = require('underscore');
var Backbone = require('backbone');
var ServiceMonitoringCollection=require('./ServiceMonitoringCollection');
var ServiceMonitoringModel = Backbone.Model.extend({
modelNAme: 'ServiceMonitoringModel',
idAttribute: 'id',
defaults: {
// todo
content_type: '',
content_graph: {
capacity: null,
performance: {
memory: new ServiceMonitoringCollection(),
cpu: new ServiceMonitoringCollection()
}
}
},
initialize: function() {
//todo
},
validate: function(attributes) {
},
parse: function(response) {
return {
content_type: response.content_type,
content_graph: {
capacity:this.getDeepJsonValue(response, 'capacity'),
performance: {
memory: new ServiceMonitoringCollection(this.getDeepJsonValue(response, 'memory'),{parse:true}),
cpu: new ServiceMonitoringCollection(this.getDeepJsonValue(response, 'cpu'),{parse:true})
}
}
};
}
});
return ServiceMonitoringModel;
});
Service.js
...
var ServiceMonitoringModel=require('common/model/server/ServiceMonitoringModel');
var ServiceMonitoringModel = new ServiceMonitoringModel();

Your problem is:
var ServiceMonitoringModel = new ServiceMonitoringModel();
You are assigning a value to your Model definition. Try:
var serviceMonitoringModel = new ServiceMonitoringModel();
Notice the lowercase s

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

Backbone update model if its already exist in collection

I'm trying to implement basic cart on backbone.js I'm completely new in it.itemsListView adds object to cartCollection. Problem is that when model is added in collection I want to increment this model quantity attribute if this model already exist in cartCollection.
var Phone = Backbone.Model.extend({});
var PhonesCollection = Backbone.Collection.extend({
model: Phone
});
var itemListView = Backbone.View.extend({
collection: null,
_template: _.template($('#listTemplate').html()),
el: $('#phonesDiv'),
events: {
'click .buyButton': '_addToCart'
},
initialize: function () {
'use strict';
this.render();
},
render: function () {
'use strict';
var rendTemplate = this._template({items: this.collection.toJSON()});
this.$el.html(rendTemplate);
return this;
},
_addToCart: function (e) {
'use strict';
var buttonId = $(e.currentTarget).attr('id');
var result = this.collection.findWhere({id: buttonId});
var purchase = {
id: result.attributes.id,
name: result.attributes.name,
price: result.attributes.price
};
cartcollection.add(new cartModel({
id: buttonId,
item: _.pick(purchase, 'id', 'name', 'price'),
itemTotalPrice: purchase.price
}));
console.log(cartcollection);
}
});
cartModel and cartCollection:
var cartModel = Backbone.Model.extend({
defaults: {
id: null,
item: {
id: null,
name: null,
price: null
},
itemTotalPrice: 0,
quantity: 1
}
});
var cartCollection = Backbone.Collection.extend({
model: cartModel,
defaults:{
totalQuantity: 0,
totalPrice: 0
}
You can do this by adding a method to your collection class. Here's one way to do it, with a method I'm calling addToCart:
var cartModel = Backbone.Model.extend({
defaults: {
quantity: 0
}
});
var cartCollection = Backbone.Collection.extend({
model: cartModel,
addToCart: function (model) {
this.add(model);
var q = model.get('quantity');
model.set('quantity', q + 1);
}
});
When you call a Backbone collection's add method, if the model you use as an argument is already in the collection, it will not be added again. Then, you can just increment the model's quantity manually.
The code below shows how this would work; you can play with it in JSBin.
var m1 = new cartModel({ name: 'm1' });
var m2 = new cartModel({ name: 'm2' });
var cart = new cartCollection();
cart.addToCart(m1);
cart.addToCart(m1);
cart.addToCart(m2);
console.log('cart length:', cart.length); // 2
console.log('m1 quantity:', m1.get('quantity')); // 2
console.log('m2 quantity:', m2.get('quantity')); // 1
$(function() {
var cartModel = Backbone.Model.extend({
defaults: {
id: null,
item: "",
quantity: 1
}
});
var cartCollection = Backbone.Collection.extend({
model: cartModel
});
// sample data
var data = [{id: 1, item:"testA"}, {id: 2, "item":"testB"}, {id: 1, "item":"testA"}, {id: 1, "item":"testA"}]
var cart = new cartCollection();
for(i in data){
var item = data[i];
// check if item already exists in collection
var model = cart.get(item.id);
if(model){
// increment model's quantity by 1
var quantity = model.get("quantity");
model.set("quantity", ++quantity);
// remove the model from collection and add updated model
cart.remove(item.id);
cart.add(model);
}else{
// if model doesn't exist in collection
// simple add it to collection
cart.add(item);
}
}
console.log(cart);
});
<script src="http://getfirebug.com/firebug-lite-debug.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>

Backbone collection inside model

I'm new to backbone and I wonder if there is a way to save previous models in a collection as an attribute of the model itself. For example,
var history = Backbone.Collection.extend({});
var myModel = Backbone.Model.extend({
defaults: {
id: '',
name: '',
history: history //history is a collection of myModel
},
//override setter so when set method is called, it will save the previous model inside history collection.
})
This would be ephemeral history
var myModel = Backbone.Model.extend({
defaults:{
id:''
},
constructor: function(){
this.history = new Backbone.Collection();
},
set: function(){
var args = Array.prototype.slice.call(arguments);
this.history.add(this.toJSON());
return Backbone.Model.prototype.set.apply(this, args);
}
});

Backbone Collection not using it's model

I have a simple Model:
App.Models.Client = Backbone.Model.extend({});
And a simple Collection:
App.Collections.Clients = App.Collections.Base.extend({
model: App.Models.Client,
urlRoot: '/clients'
});
The Base collection is simple:
App.Collections.Base = Backbone.Model.extend({
url: function() {
return App.BaseURL + this.urlRoot;
}
});
The problem is, when I do:
var c = new App.Collections.Clients();
c.fetch();
The objects in this collection are Object literals, not of type App.Model.Client
What am I doing wrong?
should it be
App.Collections.Base = Backbone.Collection.extend({
url: function() {
return App.BaseURL + this.urlRoot;
}
});
not Backbone.Model

KnockOutJS trigger parent function on child subscribe

I am currently trying to learn KnockOutJS. I thought it would be a great idea to create a simple task-list application.
I do not want to write a long text here, let's dive into my problem. I appreciate all kind of help - I am new to KnockOutJS tho!
The tasks are declared as followed:
var Task = function (data) {
var self = this;
self.name = ko.observable(data.name);
self.status = ko.observable(data.status);
self.priority = ko.observable(data.priority);
}
And the view model looks like this
var TaskListViewModel = function() {
var self = this;
self.currentTask = ko.observable();
self.currentTask(new Task({ name: "", status: false, priority: new Priority({ name: "", value: 0 }) }));
self.tasksArr = ko.observableArray();
self.tasks = ko.computed(function () {
return self.tasksArr.slice().sort(self.sortTasks);
}, self);
self.sortTasks = function (l, r) {
if (l.status() != r.status()) {
if (l.status()) return 1;
else return -1;
}
return (l.priority().value > r.priority().value) ? 1 : -1;
};
self.priorities = [
new Priority({ name: "Low", value: 3 }),
new Priority({ name: "Medium", value: 2 }),
new Priority({ name: "High", value: 1 })
];
// Adds a task to the list
// also saves updated task list to localstorage
self.addTask = function () {
self.tasksArr.push(new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() }));
self.localStorageSave();
self.currentTask().name("");
};
// Removes a task to a list
// also saves updated task list to localstorage
self.removeTask = function (task) {
self.tasksArr.remove(task);
self.localStorageSave();
};
// Simple test function to check if event is fired.
self.testFunction = function (task) {
console.log("Test function called");
};
// Saves all tasks to localStorage
self.localStorageSave = function () {
localStorage.setItem("romaTasks", ko.toJSON(self.tasksArr));
};
// loads saved data from localstorage and parses them correctly.
self.localStorageLoad = function () {
var parsed = JSON.parse(localStorage.getItem("romaTasks"));
if (parsed != null) {
var tTask = null;
for (var i = 0; i < parsed.length; i++) {
tTask = new Task({
name: parsed[i].name,
status: parsed[i].status,
priority: new Priority({
name: parsed[i].priority.name,
value: parsed[i].priority.value
})
});
self.tasksArr.push(tTask);
}
}
};
self.localStorageLoad();
}
What I want to do in my html is pretty simple.
All tasks I have added are saved to localStorage. The save function is, as you can see, called each time an element has been added & removed. But I also want to save as soon as the status of each task has been changed, but it is not possible to use subscribe here, such as
self.status.subscribe(function() {});
because I cannot access self.tasksArr from the Task class.
Any idea? Is it possible to make the self.tasksArr public somehow?
Thanks in advance!
Try this:
self.addTask = function () {
var myTask = new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() })
myTask.status.subscribe(function (newValue) {
self.localStorageSave();
});
self.tasksArr.push(myTask);
self.localStorageSave();
self.currentTask().name("");
};

Categories

Resources