Cant access helper methods inside mongoose schema - express

My directory looks like bellow
--controllers
-helper.js
--models
-userModel.js
--server.js
My helper module is like
module.exports = {
check: function() {
return 'check';
}
}
I want to access helper module inside userModel.js. So I put like
var helper = require('.././controllers/helper');
Then I do console.log(helper.check()); but it shows error helper.check is not a function Or if I do console.log(helper); only it returns {}. How to access the helper module inside models? Thank you.

Since you said it returns {}, can you please check in your helper module that you have imported userModel.js. Because it forms circular dependencies and sometimes result empty json.

Related

vuex-persistedstate not saving class methods

I'd like to preference this by saying my backgrounds in in C# so I like declaring methods within my classes. I've created a user class that contains properties and methods and I've added this to my vuex-persistedstate. One of the methods is a logout() method which clears out the properties. When I tried to invoke this method I got the following error:
TypeError: this.$data.user.logout is not a function
I then reviewed local storage and noted the user did not have reference to the class method. So I went ahead and copied the logic from the method into my vue component and it worked so I'm assuming the issue is vuex-persistedstate does not save references to methods which is why the method call did not work.
I'd like to declare the logout method in one location rather than spreading it out across vue components, what is the best practice for accomplishing this? Is it possible to do this in the class declaration or do I need a user helper file?
Sure Berco! My code is also up on GitHub so you can review it there too, but basically it seems to me that vuex does not store methods. The first file you should review is my user.js file:
https://github.com/Joseph-Anthony-King/SudokuCollective/blob/master/SudokuCollective.WebApi/client/src/models/user.js
In this file I have a method called shallow clone which takes the info received from the API and assigns it to the user:
shallowClone(data) {
if (data !== undefined) {
this.id = data.id;
this.userName = data.userName;
this.firstName = data.firstName;
this.lastName = data.lastName;
this.nickName = data.nickName;
this.fullName = data.fullName;
this.email = data.email;
this.isActive = data.isActive;
this.isAdmin = data.isAdmin
this.isSuperUser = data.isSuperUser;
this.dateCreated = data.dateCreated;
this.dateUpdated = data.dateUpdated;
this.isLoggedIn = data.isLoggedIn;
}
}
You of course don't need to abstract this away but I've found it makes the code easier to maintain.
Then in the mounted() lifecycle hook I assign the user received from the API to the component user via the shallowClone method. Please bear in mind I've done additional work on this project and the login form is now it's own component which receives the user as a prop from the app:
https://github.com/Joseph-Anthony-King/SudokuCollective/blob/master/SudokuCollective.WebApi/client/src/components/LoginForm.vue
mounted() {
let self = this;
window.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
self.authenticate();
}
});
this.$data.user = new User();
this.$data.user.shallowClone(this.$props.userForAuthentication);
},
The full code can be reviewed here:
https://github.com/Joseph-Anthony-King/SudokuCollective
I found a solution... I'm working on improving it. Basically I use the values pulled from localstorage into vuex to create a new user object in the vue component that has reference to the methods located in my user class declaration. I recalled recommendations that we should create clones of objects pulled from vuex for use within the vue component. I'm still refining the code but that's basic idea.

How to call a shared helper function from within a mutation or action in Vuex

I am trying to separate out some code that is common among many calls in my Vuex mutations. I am getting the feeling that this is discouraged but I don't understand why.
Have a look at an image of some sample code below:
I have added this 'helpers' entry in the Vuex - this obviously doesn't exist but how can I call the shared helper function 'getColumn' from mutations and/or actions?
Or do I have resort to calling a static method on a 'VuexHelper' class? :(
Something like:
Note
I have already looked at the following:
Vue Mixins - yes, something like that could work but is not
supported in Vuex - also, vue methods don't return a value...
I have looked at Modules but these still don't give me what I need, i.e. a simple re-usable function that returns a value.
Thanks
I don't see why you may want to put the helper function within the store. You can just use a plain function.
function getColumn(state, colName) {
// Do your thing.
}
const vstore = new Vuex.Store({
// ....
mutations: {
removeColumn(state, colName) {
var column = getColumns(state, colName);
}
}
};
On the other hand, if you really need that, you can access the raw module and all that's included:
var column = this._modules.root._rawModule.helpers.getColumns(state, colName);
Although this syntax is not documented and can change for later versions.
You can implement your Vuex getter as a method-style getter. This lets you pass in the specific column as an argument:
getters: {
getColumn: state => colName => {
return state.columns[colName] || null
}
}
Then getColumn can be used within the store like so:
let column = getters.getColumn('colNameString')
vuex docs > getters > method style access

addJS function not working for admin in prestashop

I am trying to add javascript file in prestashop admin using backOfficeHeader hook using a module but nothing happened. My code is given below.
public function install()
{
if (!parent::install()
|| !$this->registerHook('backOfficeHeader'))
return false;
return parent::install() &&
$this->registerHook('backOfficeHeader');
}
public function hookBackOfficeHeader() {
$this->context->controller->addJS(_MODULE_DIR_.$this->module->name.'js/hs_custom.js');
}
If you are using PS 1.5 or 1.6 you should use hook "actionAdminControllerSetMedia".
Your module installer should check which prestashop version is used and then register the needed hook.
if (version_compare(substr(_PS_VERSION_, 0, 3), '1.5', '<'))
$this->registerHook('BackOfficeHeader');
else
$this->registerHook('actionAdminControllerSetMedia');
Then you need to addJS on each hook in its version format:
PS>=1.5
public function hookActionAdminControllerSetMedia($params) {
$this->context->controller->addJS($this->_path.'views/js/hs_custom.js');
}
PS<=1.4
public function hookBackOfficeHeader($params) {
Tools::addJS($this->_path.'views/js/hs_custom.js');
}
did u try to check addJS path? I think nothing more can be possible if other JS files working.
Try to use $this->_path.
$this->context->controller->addJS($this->_path.'views/js/hs_custom.js');
1) Output path and check if it is valid.
2) Reload page and check network. Page load your script or not?
3) Remember to reset module if u change something with hooks.
4) Check module hooks.
You did several mistakes.
This is the invalid access to the property: $this->module->name. Must be $this->name. I.e., the correct code to generate a path to JavaScript file is:
_MODULE_DIR_ . $this->name . '/js/hs_custom.js'
Or like this (shorted):
$this->_path . 'js/hs_custom.js'
You are also did the double installation of the module and of the hook.
You can use the hook BackOfficeHeader, but the hook ActionAdminControllerSetMedia is preferred.
So, the correct example to add a JS and a CSS files for a back-office (i.e. for AdminController) via a module class is:
public function hookActionAdminControllerSetMedia($params)
{
// Adds your's CSS file from a module's directory
$this->context->controller->addCSS($this->_path . 'views/css/example.css');
// Adds your's JavaScript file from a module's directory
$this->context->controller->addJS($this->_path . 'views/js/example.js');
}
Here is the detailed information, how to register JavaScript in a back-office (in admin pages).
I also met this problem, there is no error and warning, all grammar is right. But cannot find my js File.
I found the reason finally. In my case there is nothing in JS file and system passes this file which has no content always.
For me "this->_path" dosn't work. My solution is to use $_SERVER['DOCUMENT_ROOT']
public function hookActionAdminControllerSetMedia($params)
{
// add necessary javascript to products back office
if($this->context->controller->controller_name == 'AdminProducts' && Tools::getValue('id_product'))
{
$this->context->controller->addJS($_SERVER['DOCUMENT_ROOT']."/modules/apl/views/js/jquery.ui.touch-punch.min.js");
}
}

Best way of global registering ClientScript?

I want to register user script globally, to be available all over the site. Now I insert in every action in my controllers:
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/script.js');
But really I understand that it's not good way...
If you are looking forward to use themes in your project, i would put some css and scripts in layout file (views/layouts/my-layout-file.php). Because if you changing theme you will be using another css and maybe sometimes another scripts, so you would not want to mix it together.
But some main css and scipts, that didn't change accross themes, i would put in main Controller (protected/components/Controller.php)
And all other controllers (/protected/controllers/) would extend this class Controller
class PageController extends Controller {
And so if all your controllers using on parent class, you can edit just parent class and add something like this
public function beforeRender( $view ) {
...
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/script.js');
...
return true;
}
And all your actions will be now using same script.
EDIT: #realtebo (in comments) pointed out to use 'beforeRender' not 'beforeAction'.
See more: Understanding the view rendering flow
You can do this in this way : initiate init function in base controller class having path protected/components/controller.php
public function init()
{
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/js/script.js');
parent::init();
}
The best way to register global js and css files I think is registering them in beforeRender() method (not in beforeAction() - because if you render json or xml this may destroy your structure) of some BaseController.
U can do like this:
1. create private attribute $_assetsUrl;
2. then in the module or controller
public function getAssetsUrl()
{
if ($this->_assetsUrl===null)
{
$assetsPath = $this->basePath.DIRECTORY_SEPARATOR.'assets';
$this->_assetsUrl = Yii::app()->assetManager->publish($assetsPath,false,-1,YII_DEBUG);
if (Yii::app()->theme!==null && is_dir($assetsPath.DIRECTORY_SEPARATOR.Yii::app()->theme->name))
$this->_assetsUrl .= DIRECTORY_SEPARATOR.Yii::app()->theme->name;
}
return $this->_assetsUrl;
}
Hope this was useful, see also this link http://www.yiiframework.com/wiki/148/understanding-assets/

How to access methods from a class based wordpress plugin?

I have a plugin which registers a post type, taxonomy and handles some business logic.
I went ahead and made my perfectly working plugin OO based and now it only works some of the time.
Its set-up like the following:
class Fruit {
public function __construct() {
add_action('init', array(&$this, 'init'));
}
public function init() {
$this->the_apple();
}
public function the_apple() {
return print $apple = 'my apple';
}
}
$fruit = new Fruit();
Then in taxonomy.php, withing the loop the following works:
$fruit->the_apple();
But once I use get_template_part with loop.php, this no longer works
$fruit->the_apple();
I get the following notice:
Notice: Undefined variable the_apple();
My fix was to use:
global $fruit;
and now it works all the time, just fyi about globals they get a bad rep. and there's namespacing issues, along with dumping everything into globals vs. using a registry.
In production i would never use the name $fruit, instead i would call it,
global $skylar_fruit;