JavaScript- calling a function defined inside a provider - javascript

I have recently taken on the development of web app that has been written in AngularJS. In one of the files, myApp.js, there is a provider that is defined as follows:
.provider('myAppConf', function($routeProvider){
var constants = {
'HOMEPAGE': '/alarms',
...
};
// Setter function for constants
this.setConstant = function(constant, value){
constants[constant.toUpperCase()] = value;
};
...
// Other setter functions
...
// Non- setter/ getter functions:
this.addElementOverview = function(){
...
var location = 'pages/elementbrowser';
...
return '/' + location;
}
function addCreatePageRoute(){
$routeProvider.when('/pages/create', {
page: {
editable: true,
title: {
...
},
layout: {
...
},
widgets: [
...
]
}
});
}
// More non- setter/ getter functions
this.$get = ['$q', '$timeout', 'myAppUI' function($q, $timeout, myAppUI){
...
}];
}).run(function(...){
...
});
On most of the pages on the site, there is a 'settings' button, which opens a dialog box that the user can use to change the settings for a given page. I have added a checkbox to that dialog box, which, when checked, I want to use to set the page on which it is checked as the 'home' page, overwriting whichever page was previously the 'home' page. If/ when the checkbox is deselected again, the home page should be set back to its original value (i.e. the /alarms page determined in the constants).
As things currently stand, I have managed to change the home page, so that it is updated to the page selected by the user- when the click 'Home' they are taken to the page on which the checkbox was selected. But as soon as they log out, their chosen home page is forgotten, and when they log in again, the default home page is their home page until they select another one.
I now want to set the user's default home page to whatever they choose as their custom home page, and am trying to use the 'setter function for constants' that is defined in the provider function above.
I have done this by calling:
myAppConf.setConstant(myAppConf.HOMEPAGE, $location.path());
when the 'Confirm' button is pressed on the dialog box (with the 'set as homepage' checkbox checked).
However, when I press the 'Confirm' button, I get a TypeError in my console which says:
TypeError: myAppConf.setConstant is not a function
I don't understand why I'm getting this error... setConstant() is defined as a function with:
this.setConstant = function(constant, value){...};
so why is the console stating that it's not a function? How can I fix this?
Edit
The function where I'm calling myAppConf.setConstant() is defined in Pages/ctrls.js as follows:
angular.module('myApp.pagse')
...
.controller('LayoutCtrl', function($scope, $route, $location, $timeout, Page, myAppConf, NotifyMgr, DialogMgr,myAppUI){
...
$scope.confirm = function(e){
...
if($scope.checkboxModel){
...
myAppConf.setConstant(myAppConf.HOMEPAGE, $location.path());
}else{
console.log("homepage not changed");
}
};

setConstant is myAppConfProvider method, not myAppConf. If it should be available both in config and run phases, it should be defined on both a provider and an instance:
.provider('myAppConf', function(){
...
var commonMethods = {
setConstant: function (constant, value) {
constants[constant.toUpperCase()] = value;
},
...
}
Object.assign(this, commonMethods, {
$get: function () {
return commonMethods;
}
})
})
A cleaner way to do this is to use constant:
.constant('myAppConf', {
_constants: { ... },
setConstant: function (constant, value) {
this[constant.toUpperCase()] = value;
},
...
})
Since getters and setters can be considered antipattern unless they are justified, a KISS alternative is just:
.constant('myAppConf', {
'HOMEPAGE': '/alarms',
...
})

Related

Emberjs How to update property on a component from route?

Hi I would like to know what's the proper way to update a property on a component from the route?.
A little background on what I want to do:
I have two custom Buttons that I called CardButtons (based on material desing) next to one blank area called description, what I want is to create a hover event that triggers an ajax call to retrive detailed data from a data base and render it on the description area.
CHECK UPDATE
So far I have created a route like this:
export default Ember.Route.extend({
selectedModule: '',
model: function () {
return {
selectedModule: 'employeeModule'
};
},
actions: {
showDescription: function (params) {
this.set('model.selectedModule', params);
}
}});
My route template call my component like this:
<div class="row">
{{sis-db-description-render idTitle=model.selectedModule}}
</div>
and the component is defined like this:
export default Ember.Component.extend({
info: null,
ready: false,
didInsertElement: function () {
this.queryData();
},
queryData: function (){
/** Does an Ember.$.post request to the API with the idTitle as param**/
}
});
the first time this executes it load perfectly the detail data but when I try to refresh the data the event does not trigger a second call. I bealive it is beacause I'm not updating the model in a proper way.
Any idea on how to update the component property?
UPDATE:
Thanks to #kumkanillam I was able to find a way on my route I added the next code:
setupController: function (controller, model) {
this._super(...arguments); //if its new/index.js route file then you can use controller argument this method.
controller.set('selectedModule', 'employeeModule');
},
actions: {
showDescription: function (params) {
console.info(params);
this.controllerFor('new.index').set('selectedModule', params);
}
}
By doing so now the view updates the content every time, I still don't know if this is the correct way to do it but it works for now.
In the below code, model is not defined in route. it's defined in corresponding controller through setupController hook.
showDescription: function (params) {
this.set('model.selectedModule', params);
}
So in your case either you can define action in controller and update model.selectedModule
If you want to do it in route,
showDescription: function (params) {
let cont = this.controllerFor('route-name');
cont.set('model.selectedModule', params);
}

Providing a template for $confirm dialogs

I'm using angular-confirm to display confirmation messages in a lot of places in my app. For example:
$confirm({
text: 'content',
title: 'title text',
ok: 'Yes',
cancel: 'No'})
.then(function() {
doSomething();
});
I want to globally change the layout in which these dialogs appear in the app. I know that angular-confirm allows you to make a global change like this:
$confirmModalDefaults.templateUrl = 'path/to/your/template';
However, this also overrides the template for all $modal.open() calls, which is not what I want.
I think that the way to do this is by a using a provider to append a template url to every $confirm call in the app but I'm not sure exactly how to do that.
How do I create a provider for $confirm and append a templateUrl parameter to every call?
Figured it out:
function config($provide) {
$provide.decorator('$confirm', confirmProvider);
}
/* #ngInject */
function confirmProvider($delegate) {
return function (data, settings) {
if (settings && !settings.template && !settings.templateUrl) {
settings.template = '<div>my confirm content</div>';
} else {
settings = {
template: '<div>my confirm content</div>'
}
}
return $delegate(data, settings);
};
So now, when $confirm() gets called with data and/or settings, it will apply my custom template unless it's been specified by the caller

Session variable not updating when going to a specific route

I'm doing something wrong while setting Session variables and handling the Router
main.js:
Template.global.onCreated(function(){
Session.setDefault("musicFilteredCategory", "latest")
});
router.js:
Router.route("/music/:category?", {
name: "music",
template: "music",
beforeAction: function () {
var category = this.params.category;
Session.set("musicFilteredCategory", category);
}
});
but when I open page "/music/latin-radio" and I check Session.get("musicFilteredCategory") I get "latest" instead of "latin-radio"
later I changed Session.setDefault("musicFilteredCategory", "latest") to outside the Template.global.onCreated({}) and the result is still the same.
What should be the best practice to do this?
I also want to add this feature once this is fixed:
when the user goes to "/music" to be redirected to "/music/:defaultMusicCategory"
PS: I'm using Meteor 1.2.0.1 & Iron Router 1.0.9
As #Kyll pointed out I should use onBeforeAction for the function to run.
This solved part of my problem, but the categories were not being changed when accessing the different routes.
Here's what I had to do:
Router.route("/music/:category?", {
name: "music",
template: "music",
onBeforeAction: function () {
var category = this.params.category;
if (category !== "undefined") {
Session.set("musicFilteredCategory", category);
}
this.render("music");
}
});
This doesn't cover the route "/music" (without the slash) so I also had to add this route, I placed it before the code above
Router.route("/music", {
name: "music",
template: "music"
});
To resolve this I had to move the Session.setDefault() outside the templates scope as they were overriding the Session established on the router, so I had to put them inside a Meteor.startup function
Meteor.startup(function () {
Session.setDefault("musicFilteredCategory", "latest");
});

marionette region undefined following init

The error ONLY occurs under a special routing circumstance when the layout (see gist link) is called by the router following a login processed in a different controller and routed here by the global event mechanism.
Everything is fine as long as an existing session is reused and there is NO Logon processed.
main code in this gist ( error at line #113 "this.headerRegion" not defined
Code blocks coming to the gist module , from logon and from router...
loginSuccess: function (user) {
vent.trigger('user:login'); //notify all widgets we have logged in
app.router.navigate('home', { trigger: true });
}
...
return marionette.AppRouter.extend({
routes: {
'home' : 'home',
...
},
home: function() {
this._showPage('home');
},
...
_showPage: function (pageName, options) {
console.log("RouterShow " +pageName);
var that = this;
//make sure we are authenicated, if not go to login
if (!Parse.User.current())
pageName = 'login';
require(['./pages/' + pageName + '/Controller'], function (PageController) {
if (that.currentPageController) {
that.currentPageController.close();
that.currentPageController = null;
}
// line below loads the layout in the gist link
that.currentPageController = new PageController(options);
that.currentPageController.show(app.regionMain)
.fail(function () {
//display the not found page
that.navigate('/not-found', { trigger: true, replace: true });
});
});
}
...
define([
'marionette',
'./Layout',
'app'
], function (
Marionette,
Layout,
app
) {
'use strict';
return Marionette.Controller.extend({
show: function (region) {
var that = this, d = new Marionette.$.Deferred();
region.show(new Layout({ })); //this layout in gist link
return d.promise();
}
});
});
pageController.show() near the end of the above block calls the Layout region in the gist
To recreate the error that ONLY OCCURs following a logon, I do the following:
Show compoundView #1 at line #57 of the gist.
click in compound view #1 firing event at line #40 of the gist ('roleList:getuser',)
swap new views #2 into EXISTING regions used for the first views at lines #113, 114
ERROR at 113, "this.headerRegion" no longer exists in the layout!
Discussion - now IMO Layout extends Marionett.ItemView and from the source, it should always have the regions defined before calling init. The constructor checks for undef "this.headerRegion" at line #23 of the gist.
My code reimplements the superclass constructor in lines 18 - 23 of the gist and it looks like "headerRegion" and "mainRegion" attributes are always defined. But, the error is :
Uncaught TypeError: Cannot call method 'show' of undefined
Layout.js:113 Marionette.Layout.extend.getUserRelation
The region properties like 'headerRegion' in your case are only available after render(), not just initialize(). From the Marionette docs:
Once you've rendered the layout, you now have direct access to all of
the specified regions as region managers.
You must be triggering those events ('roleItem:getrole', etc.) before the layout is rendered in logic outside the gist. Instead you'll need to render first if you want to implement getUserRelation() in this way.

View not updating bindings in SPA with Durandal/Knockout

I am building a SPA app with the default Durandal setup. I have multiple views returning data with ajax calls however, it is not working perfectly. I created my shell page with a search box so I can search through a list of employees shown here.
Shell.js
define(['require', 'durandal/plugins/router', 'durandal/app', 'config'],
function (require, router, app, config) {
var shell = {
router: router,
searchData: searchData,
employees: ko.observable(),
search: search,
activate: activate,
};
var searchData = ko.observable('');
function search(searchData) {
var url = '#/employeeSearch/' + searchData.searchData;
router.navigateTo(url);
}
return shell;
function activate() {
router.map(config.routes);
return router.activate(config.startModule);
}
});
shell.html
<div class="input-group">
<input type="text" class="form-control" placeholder="Search Employees" data-bind="value: searchData" />
<span class="input-group-btn">
<button type="submit" class="btn btn-default" data-bind="click: search">Search</button>
</span>
</div>
The user puts in a search and when they click the search button the view below navigates to the employeeSearch page. This does work and return the data and view I need it to here.
define(['require', 'durandal/plugins/router', 'durandal/app', 'config', 'services/logger'],
function(require, router, app, config, logger) {
var goBack = function() {
router.navigateBack();
};
function details(employee) {
var url = '#/employee/' + employee.Id + '/profile';
router.navigateTo(url);
}
var vm = {
goBack: goBack,
employees: ko.observable(),
details: details,
};
return {
activate: function (route) {
var self = this;
return self.getEmployees(route.q);
},
getEmployees: function (query) {
return $.ajax(app.url('/employees?q=' + query),
{
type: "GET",
contentType: 'application/json',
dataType: 'json',
}).then(querySucceeded).promise;
function querySucceeded(result) {
self.employees = result;
logger.log(query + ' Search Activated!', null, 'employeeSearch', true);
}
},
};
});
So then, if I try to search for another name, the url will navigate, the logger will show the value I searched for, however the view itself will not show the new results. Exploring in the Chrome debugger, I view the employees object to contain the new result set, but the view has still not updated. If I refresh the page however, the view does properly show up I have viewed multiple questions on here with similar issues about keeping your data calls in the activate method, make sure the data returns a promise before completing the activate method, and putting DOM manipulation in the viewAttached.
Javascript is not rendering in my SPA
How to use observables in Durandal?
HotTowel: Viewmodel lose mapping when navigating between pages
After putting those practices in my code, I am still having problems getting the view to update correctly.
Are there any other Durandal/Knockout properties I need to be aware of? How can I get the bindings to update every time I navigate to a view with (router.navigateTo(url);). I have set my shell properties (cacheViews: true) to true and false but nothing seems to change.
This is one of many problems I have been having with building SPA apps with Durandal. Trying not to give up yet.
I cant test this quick but a think you handle the observable wrong.
I suspect the "result" var is an array of employees. In this case you might handle this with an observableArray (http://knockoutjs.com/examples/collections.html)
And you cant set the value directly like self.employees
You must call the observable function to set the value like
function querySucceeded(result) {
self.employees(result)
logger.log(query + ' Search Activated!', null, 'employeeSearch', true);
}
In your samples you have not shown/mentioned where knockout is being loaded. If you are using Durandal 2.0 then add the following line to the top of your main.js file above your existing define statement
define('knockout', ko);

Categories

Resources