Ember select selectionbinding observable not working, - javascript

App.Select2Users = Ember.Select.extend({
attributeBindings: ['class'],
selectedValueBinding: this.get('selectionBinding'),
didInsertElement: function () {
Ember.run.scheduleOnce("afterRender", this, "processChildElements");
},
value: Ember.computed(function(key, value){
alert('haah');
}),
processChildElements: function () {
var self = this;
$(this.$()).select2({}).on('change', function (e) {
var context = self.get('context');
var currentValues = self.get(self.selectionBinding._from);
e.val.forEach(function (val) {
if (!_.contains(currentValues, val))
currentValues.push(val);
});
self.set(self.selectionBinding._from, currentValues);
})
},
propertyWillChange: function () { alert('se'); },
willDestroyElement: function () {
$(this.$()).select2('destroy');
}
});
Above is my selectview. I'm using select2 on a select multiple.Below is my controller,
App.NewController = Ember.Controller.extend({
selectedUsers:[],
users: [{ userId: "Logan", department: "Frontline" }, { userId: "Logan2", department: "Frontline2" }],
users: null,
userSelected: function () {
alert('user selected');
}.observes('selectedUsers.#each'),
});
The plugin works and updates the selectedUsers each time i select an item from the selectlist. But the function userSelected doesnt get invoked. From what i know, whenever an observable property is modified, the even will fire. Am i correct?

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

Access object context from prototype functions JavaScript

I have problems with object scope.
Here is my class code
// Table list module
function DynamicItemList(data, settings, fields) {
if (!(this instanceof DynamicItemList)) {
return new DynamicItemList(data, settings, fields);
}
this.data = data;
this.settings = settings;
this.fields = fields;
this.dataSet = {
"Result": "OK",
"Records": this.data ? JSON.parse(this.data) : []
};
this.items = this.dataSet["Records"];
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
this.dataHiddenInput = $(this.settings["hidden-input"]);
}
DynamicItemList.RESULT_OK = {"Result": "OK"};
DynamicItemList.RESULT_ERROR = {"Result": "Error", "Message": "Error occurred"};
DynamicItemList.prototype = (function () {
var _self = this;
var fetchItemsList = function (postData, jtParams) {
return _self.dataSet;
};
var createItem = function (item) {
item = parseQueryString(item);
item.id = this.generateId();
_self.items.push(item);
return {
"Result": "OK",
"Record": item
}
};
var removeItem = function (postData) {
_self.items = removeFromArrayByPropertyValue(_self.items, "id", postData.id);
_self.dataSet["Records"] = _self.items;
_self.generateId = makeIdCounter(findMaxInArray(_self.dataSet["Records"], "id") + 1);
return DynamicItemList.RESULT_OK;
};
return {
setupTable: function () {
$(_self.settings["table-container"]).jtable({
title: _self.settings['title'],
actions: {
listAction: fetchItemsList,
deleteAction: removeItem
},
fields: _self.fields
});
},
load: function () {
$(_self.settings['table-container']).jtable('load');
},
submit: function () {
_self.dataHiddenInput.val(JSON.stringify(_self.dataSet["Records"]));
}
};
})();
I have problems with accessing object fields.
I tried to use self to maintain calling scope. But because it is initialized firstly from global scope, I get Window object saved in _self.
Without _self just with this it also doesn't work . Because as I can guess my functions fetchItemsList are called from the jTable context and than this points to Window object, so I get error undefined.
I have tried different ways, but none of them work.
Please suggest how can I solve this problem.
Thx.
UPDATE
Here is version with all method being exposed as public.
// Table list module
function DynamicItemList(data, settings, fields) {
if (!(this instanceof DynamicItemList)) {
return new DynamicItemList(data, settings, fields);
}
this.data = data;
this.settings = settings;
this.fields = fields;
this.dataSet = {
"Result": "OK",
"Records": this.data ? JSON.parse(this.data) : []
};
this.items = this.dataSet["Records"];
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
this.dataHiddenInput = $(this.settings["hidden-input"]);
}
DynamicItemList.RESULT_OK = {"Result": "OK"};
DynamicItemList.RESULT_ERROR = {"Result": "Error", "Message": "Error occurred"};
DynamicItemList.prototype.fetchItemsList = function (postData, jtParams) {
return this.dataSet;
};
DynamicItemList.prototype.createItem = function (item) {
item = parseQueryString(item);
item.id = this.generateId();
this.items.push(item);
return {
"Result": "OK",
"Record": item
}
};
DynamicItemList.prototype.setupTable = function () {
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: this,
fields: this.fields
});
};
DynamicItemList.prototype.load = function () {
$(this.settings['table-container']).jtable('load');
};
DynamicItemList.prototype.submit = function () {
this.dataHiddenInput.val(JSON.stringify(this.dataSet["Records"]));
};
DynamicItemList.prototype.removeItem = function (postData) {
this.items = removeFromArrayByPropertyValue(this.items, "id", postData.id);
this.dataSet["Records"] = this.items;
this.generateId = makeIdCounter(findMaxInArray(this.dataSet["Records"], "id") + 1);
return DynamicItemList.RESULT_OK;
};
DynamicItemList.prototype.updateItem = function (postData) {
postData = parseQueryString(postData);
var indexObjToUpdate = findIndexOfObjByPropertyValue(this.items, "id", postData.id);
if (indexObjToUpdate >= 0) {
this.items[indexObjToUpdate] = postData;
return DynamicItemList.RESULT_OK;
}
else {
return DynamicItemList.RESULT_ERROR;
}
};
Your assigning a function directly to the prototype. DynamicItemList.prototype= Normally it's the form DynamicItemList.prototype.somefunc=
Thanks everyone for help, I've just figured out where is the problem.
As for last version with methods exposed as public.
Problematic part is
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: {
listAction: this.fetchItemsList,
createAction: this.createItem,
updateAction: this.updateItem,
deleteAction: this.removeItem
},
fields: this.fields
});
};
Here new object is created which has no idea about variable of object where it is being created.
I've I changed my code to the following as you can see above.
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: this,
fields: this.fields
});
And now it works like a charm. If this method has drawbacks, please let me know.
My problem was initially in this part and keeping methods private doesn't make any sense because my object is used by another library.
Thx everyone.
You need to make your prototype methods use the this keyword (so that they dyynamically receive the instance they were called upon), but you need to bind the instance in the callbacks that you pass into jtable.
DynamicItemList.prototype.setupTable = function () {
var self = this;
function fetchItemsList(postData, jtParams) {
return self.dataSet;
}
function createItem(item) {
item = parseQueryString(item);
item.id = self.generateId();
self.items.push(item);
return {
"Result": "OK",
"Record": item
};
}
… // other callbacks
$(this.settings["table-container"]).jtable({
title: this.settings['title'],
actions: {
listAction: fetchItemsList,
createAction: createItem,
updateAction: updateItem,
deleteAction: removeItem
},
fields: this.fields
});
};

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?

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.

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