Execution javascript function inside handlebars - javascript

I try to execute JS function in hbs for displaying html depend on data from MongoDB. And now i cant put handlebars inside handlebars
{{#if_eq author '{{ ../user._id }}' }}
читать больше
<form action="/article/{{ this._id }}?_method=DELETE" method="post" class="more">
<button type="submit" name="button">удалить</button>
</form>
{{/if_eq}}
and:
hbs.handlebars.registerHelper('if_eq', function(a, b, opts) {
if (a == b) {
return opts.fn(this);
} else {
return opts.inverse(this);
}
});
It doesnt work. How handlebars-helper can help in this situation?
I also tried to execute function and put there variable:
hbs.handlebars.registerHelper('isApply', function(req, opts) {
let user = req.user.name;
if (this.name === 'user') {
console.log(user);
return opts.fn(this);
} else {
return opts.inverse(this);
}
});
and do this in my template:
{{#isApply}}
читать больше
<form action="/article/{{ this._id }}?_method=DELETE" method="post" class="more">
<button type="submit" name="button">удалить</button>
</form>
{{/isApply}}
But it also doesnt work, cuz user: undefined.
Please can you help to find a solution of this issue?

Related

Pass value from button in HTML to function in Javascript

I'm trying to pass some value from button, which is located in HTML document, to the Javascript function, which is located in other document, but it doesn't work. I also tried with getElementById(), but it still didn't work. What's the problem? I would appreciate any help. Thanks in advance!
index.html
<script src="../scripts/appearances_2.js"></script>
/...
<div id="appearances_2_chart">
<div>
<button id="starting" onclick="update_view('starting')">Starting players</button>
<button id="substitution" onclick="update_view('substitution')">Substitution players</button>
</div>
</div>
/...
appearances_2.js
document.addEventListener('DOMContentLoaded', function(e) {
//...
function update_view(id) {
d3.csv("../../data/appearances.csv", function(data) {
data.sort(function(b, a) {
if (id == 'starting')
{
return a.starting - b.starting;
}
else if (id == 'substitution')
{
return a.substitution - b.substitution;
}
});
/...
You can use, event as an object to be passed and access the value as (in order to get the id),
event.target.getAttribute('id')
You need to modify the button code as,
<button id="starting" onclick="update_view(event)">Starting players</button>
and in function,
update_view(event){....}
and access the id using the target object as mentioned in the first code.
Update:-
function update_view(event) {
d3.csv("../../data/appearances.csv", function (data) {
data.sort(function (b, a) {
if (event.target.getAttribute('id') === 'starting') {
return a.starting - b.starting;
}
else if (event.target.getAttribute('id') === 'substitution') {
return a.substitution - b.substitution;
}
})
})
};
<button id="starting" onclick="update_view(event)">Starting players</button>
<button id="substitution" onclick="update_view(event)">Substitution players</button>

Having problems with the JavaScript/jquery and c# implementation

I am following a 3 year old c# course on udemy and am unable to solve the problem regarding the implementation of javascript/jquery code. I am suppose to connect the registration code (via jquery/javascript) with a subscription, however my textbox does not work regardless of the information I insert in it, it is not displaying any text, and it should be displaying different messages such are - Could not register the code., The code was successfully added.
Here is my code:
RegisterCodeController:
public class RegisterCodeController : Controller
{
public async Task<ActionResult> Register(string code)
{
if(Request.IsAuthenticated)
{
var userId = HttpContext.GetUserId();
var registred = await SubscriptionExtension.RegisterUserSubscriptionCode(userId, code);
if (!registred) throw new ApplicationException();
return PartialView("_RegisterCodePartial");
}
return View();
}
_RegisterCodePartial:
#if(Request.IsAuthenticated)
{
<div class="panel panel-primary register-code-panel">
<div class="panel-heading">
<h4 class="panel-title">Register Code</h4>
</div>
<div class="panel-body input-group">
<input type="text" class="form-control" placeholder="Enter code here..." />
<button class="btn btn-primary input-group-btn" type="button" >Submit
<h3 class="panel-title">Submit</h3>
</button>
</div>
<div class="alert alert-danger hidden">Could not register code</div>
</div>
}
RegisterCode.js
$(function () {
var code = $(".register-code-panel input");
function displayMessage(success, message)
{
var alert_div = $(".register-code-panel .alert");
alert_div.txt(message);
if (success)
alert_div.removeClass('alert-danger').addClass('alert-success');
else
alert_div.removeClass('alert-success').addClass('alert-danger');
alert_div.removeClass('hidden');
}
$(".register-code-panel button").click(function (e) {
$(".register-code-panel .alert").addClass('hidden');
if (code.val().length == 0)
{
displayMessage(false, "Enter a code");
return;
}
$.post('/RegisterCode/Register', { code: code.val() },
function (data)
{
displayMessage(true, "The code was successfully added. /n/r Please reload the page.");
code.val('');
}).fail(function (xlr, status, error) {
displayMessage(false, "Could not register the code.");
});
});
});
You are making a POST request but looking at your controller action method it looks like a GET. Thus change your API call $.post('/RegisterCode/Register', { code: code.val() }, to $.get('/RegisterCode/Register', { code: code.val() }, probably and use a HTTP verb explicitly in your action method
[HttpGet]
public async Task<ActionResult> Register(string code)
{
}
Solved, I had the RegisterCode.css file with the same name as RegisterCode.js file, it seems to me this caused some confusion while retrieving data in the Bundle.config, so I renamed the .js file and now it works!

Meteor/Iron Router - When/Where to run JS to swap to WYSIWYG

I'm trying to figure out where is the best place to run a jQuery plugin that replaces a textarea (with a reactive value). It needs to be called after the textarea has been assigned the value.
I've tried various places. The most correct place I've tried seems to be in the templates onAfterAction callback, in a Meteor.defer. This works about 95% of the time.
Something like this:
MyController = RouteController.extend({
waitOn: function () {
return Meteor.subscribe('post', this.params._id);
},
onAfterAction: function () {
Meteor.defer(function () {
$('.make-wysiwyg').wysiwyg();
});
}
});
However, occasionally it doesn't. If I start bouncing between posts really quick, occasionally one will apparently run before the textarea has data and fail to display property (it'll be empty, because it needs the value before wysiwyg() is called).
I've eliminated the wysiwyg() function itself as the culprit by replacing that line with:
$('.make-wysiwyg').each(function () {console.log($(this).val())});
And I can clearly see every so often it'll print empty value fields for no apparent reason.
I'm not sure if the template or publish() function could be a culprit, so I'll supply them as well.
Any ideas greatly appreciated.
Template:
<template name="adminPostsEdit">
<h1>Edit Post</h1>
<form id="edit-post" class="{{isNewClass}}" method="post">
<label for="post-title">Title</label>
<input id="post-title" value="{{post.title}}">
<label for="post-slug">Slug</label>
<input id="post-slug" value="{{post.slug}}">
<label for="post-content">Content</label>
<textarea id="post-content" class="make-wysiwyg">{{post.content}}</textarea>
<label for="post-excerpt">Excerpt</label>
<textarea id="post-excerpt" class="make-wysiwyg">{{post.excerpt}}</textarea>
{{#if post.published}}
<button value="save">Save</button>
<button value="unpublish">Unpublish</button>
{{else}}
<button value="save">Save Draft</button>
<button value="publish">Publish</button>
{{/if}}
<button value="cancel">Cancel</button>
</form>
</template>
publish():
Meteor.publish('post', function (id) {
return Posts.find({_id: id});
});
Helpers:
Template.adminPostsEdit.helpers({
post: function () {
return Posts.findOne();
},
isNewClass: function () {
return !this.id ? 'new' : '';
}
});
You should do that in the template's render function.
Template.adminPostsEdit.rendered = function() {
$('.make-wysiwyg').wysiwyg();
})

Scope not updating changes in the model

I have an expandable form that generates an object with two attributes, a title and description. This object successfully submits to my database as a json object. I'm currently using an Angular (1.3.2) front end that interacts with Tastypie as the interface layer with my Django (1.7) backend. The problem is that I never observe updates to my home page after adding a new object to the db. I need to refresh the page for the object to appear which is not ideal.
home.html
<div class="protocol-list-container">
<div ng-app="protocolApp"
id="protocol-list">
<div class="new-protocol-container" ng-controller="protoCtrl">
<h4>Add New Protocol</h4>
<button type="button"
ng-click="toggle()"
id="id_new">
<span class="glyphicon glyphicon-plus"></span>
</button>
<div ng-hide="visible" class="protocol-new">
<form name="newProtocolForm" novalidate>
<input type="text"
id="id_new_title"
placeholder="Title"
ng-model="protocol.title"
required /><br>
<input type="text"
id="id_new_desc"
placeholder="Description"
ng-model="protocol.description"
required /><br><br>
<input type="submit"
id="id_submit_new_protocol"
value="New Protocol"
ng-click="submit(protocol)"
ng-disabled="newProtocolForm.$invalid">
</form>
{% verbatim %}
<pre>form = {{ protocol | json}}</pre>
{% endverbatim %}
</div>
<div class="protocol">
<h4>My Protocols</h4>
<li ng-repeat="protocol in protocols">
{% verbatim %}
<div><span ng-bind="protocol.title"></span></div>
{% endverbatim %}
<div> - <span ng-bind="protocol.description"></span>
</li>
<br>
</div>
</div>
</div>
app.js
angular.module('protocolApp', [])
.factory('protocolFactory', ['$http', function($http) {
var urlBase = '/api/v1/protocol/';
var protocolFactory = {};
protocolFactory.getProtocols = function() {
console.log('getProtocols called');
return $http.get(urlBase);
};
protocolFactory.addProtocol = function(protocol) {
console.log('addProtocol called');
return $http.post(urlBase, protocol);
};
return protocolFactory;
}])
.controller('protoCtrl', ['$scope', 'protocolFactory',
function ($scope, protocolFactory) {
$scope.visible = true;
var self = this;
getProtocols();
function getProtocols() {
protocolFactory.getProtocols()
.success(function(data) {
$scope.protocols = data;
})
.error(function(error) {
console.log('error retrieving protocols');
});
}
$scope.toggle = function() {
$scope.visible = !$scope.visible;
var self = this;
var protocol = {};
self.submit = function() {
var protocol = {title: self.title, description: self.description};
console.log('clicked submit with ', self.protocol);
protocolFactory.addProtocol(self.protocol)
.success(function(response) {
console.log('protocol added');
$scope.protocol = null;
})
.error(function(error) {
console.log('post to api failed');
});
// gives the behavior I want, but ultimately crashes chrome
// $scope.$watch('protocols', function(newVal, oldVal) {
// protocolFactory.getProtocols()
// .success(function(data) {
// $scope.protocols = data;
// console.log('watcher data', data);
// });
// }, true);
};
};
}]);
I've done some testing with a $scope.$watch function (commented out), but this either shows the new object and never stops (true removed) or does not update (but tells me that there is an extra object in the data based on the console statement) (true present).
Any help would be appreciated.
When the database gets updated, how does the front end know that it should get the latest data unless we tell it to ? You don't have some kind of sockets between the server and front end, looking for events and making the front end to get the latest data...
So, When you post the data to backend and database got updated, make a call to getProtocols(), in the success callback of submit.
In your case of using $watch(), you are repeatedly getting the protocols from backend, which updated the scope variable, which again fired the callback repeatedly and browser crashed.

Why is my variable "unresolved" in AngularJS

I have a really stupid question and I'm hoping someone can help me understand AngularJS a little better here whilst I trawl through more documentation... please be aware that I have been working with AngularJS for a week now as I have inherited a project off a colleague, anyway...
The unit tests associated with my project are failing with the following error message "scope.signupForm is undefined in /Users/.../.../.../app/login/login.js"
In WebStorm my code is being highlighted (underlined grey) with the following messages "Unresolved Variable signinForm" & "Unresolved Variable signupForm", the code where this is being raised is below...
this is part of the controller...
function LoginController($scope, userService) {
$scope.loggedInUser = null;
$scope.signIn = function (user) {
console.log("SignIn");
$scope.loggedInUser = { userName: user.userName };
$scope.user = undefined;
$scope.signinForm.$setPristine(); // Error here is "Unresolved Variable signinForm"
};
$scope.register = function (user) {
console.log("Register");
$scope.loggedInUser = user;
$scope.user = undefined;
console.log(user);
userService.addUser(user);
$scope.signupForm.$setPristine();// Error here is "Unresolved Variable signupForm"
};
$scope.signOut = function () {
console.log("SignOut");
$scope.loggedInUser = undefined;
$scope.signInVisible = false;
};
... // more code here
Now this is my HTML code contained in a View (for want of a better word)
<div id="login-signin" class="loginLeftBox">
<form name="signinForm" novalidate ng-submit="signIn(loginUser)" autocomplete="off">
<div> ... Form Stuff...</div>
</form>
<div ng-show="signinForm.userName.$dirty && signupForm.userName.$invalid">
... Validation Stuff...
</div>
<div ng-show="signinForm.password.$dirty && signupForm.password.$invalid">
... Validation Stuff...
</div>
</div>
<div id="login-register" class="loginRightBox">
<form name="signupForm" novalidate ng-submit="register(user)" autocomplete="off">
... Form Stuff...
</form>
</div>
Any explanations would be appreciated...
You have to place your controller in the same level as the form:
<form name="signinForm" ng-controller="SinginFormCtrl" ...>
Then the SinginFormCtrl will have the signinForm in scope, e.g.:
function SinginFormCtrl($scope, userService) {
$scope.signIn = function (user) {
...
$scope.signinForm.$setPristine(); // WILL WORK NOW
};
...
}
This probably means that you will have to restructure your code a bit.
I found that, after writing $scope to the console that both $scope.signinForm & $scope.signupForm where present and defined! Thus I added the following condition to the controller and now all the Unit Tests seem to work?
reset = function(){
if($scope.signinForm){
$scope.signinForm.$setPristine();
}
if($scope.signinForm){
$scope.signupForm.$setPristine();
}
};
Not sure if this is a solution or a hack?

Categories

Resources