Meteor + polymer without blaze - javascript

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?

Related

Vue Watch doesnt Get triggered when using axios

Hey guys I have this code that fetches data from database usin axios, and in the .then() function I set a data property, watch doesnt trigger. Here is some code that I currently have. And thank you in advance!
export default {
name: '..',
data() {
return {
autocompleteOn: false
}
},
watch: {
autocompleteOn(oldVal, newVal) {
console.log('autocomplet') // doesnt trigger this
}
},
methods: {
fetchAutocompleteResults: _.debounce((filter) => {
let $this = this;
let data = {
filter: filter,
page: $this.page
};
filter.resources.response = [];
filter.loading = true;
axios.post(BASE_URL + '/search/filter', data).then(function(response) {
if (response.data.length) {
filter.autocompleteOn = true;
$this.autocompleteOn = true;
filter.resources.response = filter.resources.response.concat(response.data);
$this.currentFilter = filter;
$this.page++;
console.log($this.autocompleteOn); // this is correct
}
filter.loading = false;
});
}, 300)
}
}
The debounce with an arrow function is making the this be something other than the Vue instance (e.g. window).
Instead of:
methods: {
fetchAutocompleteResults: _.debounce((filter) => {
Use:
methods: {
fetchAutocompleteResults: _.debounce(function (filter) {
// ^^^^^^^^ ^^^
Demo:
new Vue({
el: '#app',
data() {
return {
autocompleteOn: false
}
},
watch: {
autocompleteOn(oldVal, newVal) {
console.log('autocomplet') // doesnt trigger this
}
},
methods: {
fetchAutocompleteResults: _.debounce(function (filter) { // CHANGED from arrow function
let $this = this;
let data = {
filter: filter,
page: $this.page
};
filter.resources.response = [];
filter.loading = true;
// changed data for demo
data = [{title: 'foo', body: 'bar', userId: 1}];
// changed URL for demo
axios.post('https://jsonplaceholder.typicode.com/posts', data).then(function(response) {
if (response.data.length) {
filter.autocompleteOn = true;
$this.autocompleteOn = true;
filter.resources.response = filter.resources.response.concat(response.data);
$this.currentFilter = filter;
$this.page++;
console.log($this.autocompleteOn); // this is correct
}
filter.loading = false;
});
}, 300)
}
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.5/lodash.min.js"></script>
<div id="app">
<button #click="fetchAutocompleteResults({resources: {}})">fetchAutocompleteResults</button>
</div>

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

Variables staying null in vue.js application for shopify

I am building up a vue.js application for Shopify's JavaScript Buy SDK, but i am having problems with one variable not being updated.
Basically the shopClient variable is updated, but the shopCart stays null for some reason.
var vueApp = new Vue({
el: '#shopify-app',
created: function() {
this.setupShopAndCart();
},
data: {
shopCart: null,
shopClient: null,
},
methods: {
setupShopAndCart: function() {
this.shopClient = ShopifyBuy.buildClient({
apiKey: 'xxx',
domain: 'xxx.myshopify.com',
appId: '6'
});
if(localStorage.getItem('lastCartId')) {
this.shopClient.fetchCart(localStorage.getItem('lastCartId')).then(function(remoteCart) {
this.shopCart = remoteCart;
cartLineItemCount = this.shopCart.lineItems.length;
console.log(this.shopCart.checkoutUrl);
console.log("fetching");
});
} else {
this.shopClient.createCart().then(function (newCart) {
this.shopCart = newCart;
localStorage.setItem('lastCartId', this.shopCart.id);
cartLineItemCount = 0;
console.log(this.shopCart.checkoutUrl);
console.log("failing");
});
}
}, //setupShop end
}
});
You have a problem with scoping. this in the promise isn't the vue instance.
try this
var vueApp = new Vue({
el: '#shopify-app',
created: function() {
this.setupShopAndCart();
},
data: {
shopCart: null,
shopClient: null,
},
methods: {
setupShopAndCart: function() {
var self = this;
this.shopClient = ShopifyBuy.buildClient(
{
apiKey: 'xxx',
domain: 'xxx.myshopify.com',
appId: '6'
}
);
if(localStorage.getItem('lastCartId')) {
this.shopClient.fetchCart(localStorage.getItem('lastCartId')).then(
function(remoteCart) {
self.shopCart = remoteCart;
cartLineItemCount = self.shopCart.lineItems.length;
console.log(self.shopCart.checkoutUrl);
console.log("fetching");
}
);
} else {
this.shopClient.createCart().then(
function (newCart) {
self.shopCart = newCart;
localStorage.setItem('lastCartId', self.shopCart.id);
cartLineItemCount = 0;
console.log(self.shopCart.checkoutUrl);
console.log("failing");
}
);
}
}, //setupShop end
}
});
That stores the local vue instance in the self variable that is accessable to the promises allowing you to set the shopCart variable.
EDIT: As indicated lambda functions are correct if using ES2015 or newer
var vueApp = new Vue({
el: '#shopify-app',
created: function() {
this.setupShopAndCart();
},
data: {
shopCart: null,
shopClient: null,
},
methods: {
setupShopAndCart: function() {
this.shopClient = ShopifyBuy.buildClient(
{
apiKey: 'xxx',
domain: 'xxx.myshopify.com',
appId: '6'
}
);
if(localStorage.getItem('lastCartId')) {
this.shopClient.fetchCart(localStorage.getItem('lastCartId')).then(
(remoteCart) => {
this.shopCart = remoteCart;
cartLineItemCount = this.shopCart.lineItems.length;
console.log(this.shopCart.checkoutUrl);
console.log("fetching");
}
);
} else {
this.shopClient.createCart().then(
(newCart) => {
this.shopCart = newCart;
localStorage.setItem('lastCartId', this.shopCart.id);
cartLineItemCount = 0;
console.log(this.shopCart.checkoutUrl);
console.log("failing");
}
);
}
}, //setupShop end
}
});

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

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

Ember select selectionbinding observable not working,

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?

Categories

Resources