Backbone.js underscore template rendering issue - flask

I'm having a hard time getting server data to render in my underscore template. The underscore markup displays on the page as a string, for example inside the div, you can see <%= test %>.
I'm using backbone, require, and the running on the python flask framework.
I've tried multiple different approaches as suggested in a variety of posts but I can't seem to figure out what the issue is. I'm not seeing any errors in the console. Everything is working as expected, and the request to the server is executing, and data is being returned appropriately so at least that portion of the backbone app is working. The router is rendering the appropriate page, but the _.template, just doesn't seem to be working.
Here's the view:
define(['jquery',
'underscore',
'backbone',
'bootstrap',
'text!/static/html/templates/security.html'
],function($,_,Backbone,b, security){
var SecurityView = Backbone.View.extend({
template: _.template($(security).html()),
events: {
"click #submit": 'submit_security'
},
initialize: function(options) {
this.options = options || {};
var currentInstance = this;
},
render: function() {
var that = this;
var template = this.template({test: 'blahblah'});
this.$el.html(template);
return this;
},
});
return SecurityView;
});
The Router:
define(['jquery', 'underscore', 'backbone',
'models/login', 'models/register', 'models/security',
'collections/questions',
'views/login', 'views/register', 'views/security'
],
function($,_,Backbone, Login, Register, Security,
Questions,
LoginView, RegisterView, SecurityView) {
var app = {};
app.models = app.models || {};
app.collections = app.collections || {};
app.current_content = null;
app.current_dialog = null;
app.current_logout = null;
var Router = Backbone.Router.extend({
routes: {
"login": "login",
"register": "register",
"book_writer": "book_writer",
"book_setup": "book_setup",
"error_page": "error_page",
"security": "security_questions"
},
replace_cur_content: function(view, nologout){
//if (app.current_content) {
// app.current_content.remove();
//}
app.current_content = view;
if (view) {
var display = view.render();
$('#app').append($(display.el));
}
},
security_questions: function() {
app.models.security = new Security();
app.models.security.fetch({
reset: true,
success: function(model) {
var state = model.get('session_state');
if (state === 'ready') {
var securityView = new SecurityView({model: model});
app.AppRouter.replace_cur_content(securityView);
} else if (state === 'error') {
// error page
} else if (state === 'logged_out') {
Backbone.history.navigate('login', {trigger: true});
}
}
});
}
});
app.AppRouter = new Router();
$(document).ajaxError(function(event, xhr){
if (xhr.status == 401) {
console.log('Ajax Error - 401');
app.AppRouter.login();
} else if (xhr.status == 403) {
console.log('Ajax Error - 403');
app.AppRouter.noverify();
} else if (xhr.status == 404) {
console.log('Ajax Error - 404');
app.AppRouter.notfound();
} else {
app.AppRouter.error();
}
});
return app;
});
The template:
<div class="form-content">
<div class="form-box">
<div class="form" id="security_form">
<h3 class="form-heading">Security Questions: </h3>
<%= test %>
</div>
</div>
</div>
No error messages are available in the console. Expected is: the underscore markup should not display as text on the page after render.

Related

Kendo Multi-select in cascading scenario unable to populate initial values

I'm using Telerik for MVC and trying to get the multi-select to populate with the initial values in an Edit scenario.
<script>
function filterProducts() {
return {
manufacturerId: $("#ServiceBulletinItem_ManufacturerId").val()
};
}
function onManufacturerChange(e) {
var v = e.sender.dataItem().Value;
$.post("#Url.Action("GetCascadeProducts", "Components")", { manufacturerId: v }, function (result) {
var grid = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect")
grid.setDataSource(result)
});
}
function InitialPopulate(manId) {
$.post("#Url.Action("GetCascadeProducts", "Components")", { manufacturerId: manId }, function (result) {
var grid = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect")
grid.setDataSource(result)
});
}
$(document).ready(function () {
$('.control-datepicker').Zebra_DatePicker();
var m = $("#ServiceBulletinItem_ManufacturerId").val();
InitialPopulate(m);
});
</script>
<div class="form-group">
#Html.LabelFor(m => m.ManufacturerList, "Manufacturer", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#(Html.Kendo().DropDownListFor(m => m.ServiceBulletinItem.ManufacturerId)
.HtmlAttributes(new { #class = "col-md-6 form-control" })
.Filter("contains")
.DataValueField("Value")
.DataTextField("Text")
.BindTo((IEnumerable<SelectListItem>)Model.ManufacturerSelectList)
.HtmlAttributes(new { style = "width:70%;" }).Events(e =>
{
e.Change("onManufacturerChange");
})
)
</div >
</div >
<div class="form-group">
#Html.LabelFor(m => m.ProductList, "Product", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#(Html.Kendo().MultiSelectFor(m => m.ServiceBulletinItem.ApplicableProducts)
.AutoClose(false)
.DataTextField("ProductName")
.DataValueField("ProductId")
.Placeholder("Select products...")
)
</div>
</div>
I'm trying to populate the manufacturer drop down and the Product multiSelect. The ApplicableProducts item is an IEnumerable representing the ProductId's of all those previously selected and I know that when I select the manufacturer and it calls the GetCascadeProducts controller method it will return back a collection of ProductId and ProductName for all the manufacturers products of which those productId is the ApplicableProducts property should exist.
On document.ready I can call the InitialPopulate method with the manufacturerID which will populate the multiSelect items but can't seem to populate the initial values.
I couldnt get the binding working correctly so ended up using
#(Html.Kendo().MultiSelect()
.Name("ServiceBulletinItem_ApplicableProducts")
.AutoClose(false)
.DataTextField("ProductName")
.DataValueField("ProductId")
.Placeholder("Select products 2...")
.AutoBind(false)
)
and then on the using the following code on document ready to make an ajax call to populate the manufacturer and product controls
function PopulateProductsInitial(manId) {
$.post("#Url.Action("GetCascadeProducts", "Components")", { manufacturerId: manId }, function (result) {
var grid = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect")
grid.setDataSource(result);
var s = $("#ServiceBulletinItem_Id").val();
$.post("#Url.Action("GetSBProducts", "ServiceBulletins")", { Id: s}, function (result) {
var arr = [];
result.forEach(function (element) {
arr.push(element.ProductId);
});
var grid = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect")
grid.value(arr);
});
});
}
}
$(document).ready(function () {
//Populate Initial Values
PopulateProductsInitial($("#ServiceBulletinItem_ManufacturerId").val());
$('#YourButton').click(SendForm);
});
The problem then became sending the selected items back to the controller when the edit was complete which again seemed convoluted because the control was not bound and therefore I had to make an Ajax call to submit the data.
function SendForm() {
var items = $("#ServiceBulletinItem_ApplicableProducts").data("kendoMultiSelect").value();
//Manipulate into ServiceBulletinViewModel for the save
var data = {
Id: $("#ServiceBulletinItem_Id").val(),
ServiceBulletinItem: {
Id: $("#ServiceBulletinItem_Id").val(),
ManufacturerId: $("#ServiceBulletinItem_ManufacturerId").val(),
IssueDate: $('#ServiceBulletinItem_IssueDate').val(),
Heading: $('#ServiceBulletinItem_Heading').val(),
Details: $('#ServiceBulletinItem_Details').val(),
Url: $('#ServiceBulletinItem_Url').val(),
SelectedProducts: items
}
}
$.ajax({
type: 'POST',
url: '/ServiceBulletins/Edit',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
//Your success code here..
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
},
error: function (jqXHR) {
if (jqXHR.status === 200) {
alert("Value Not found");
}
}
});
}
It all seemed a lot more convoluted than any of the demo's that teleriks and I couldnt find any good examples of binding from remote sources which looked similar.
As the binding is convention based I'm wondering if its possible to simplify the ajax calling for the post functionality with the correct naming of the controls so that I can simply get the selected items on the multiselect control or if the ajax post is the way to go.

The changed value is not reflecting on the input field in ReactJS, TestUtils

I am using ReactJs and Mocha and trying few unit tests. I have two mandatory form fields First Name and Last Name. I am trying to test the validation where if only one field is entered, the other field displays the missing value validation error.
Below code simulates the changes to the value and simulates the form submit.
TestUtils.Simulate.change(firstNameElement , {target: {value: 'Joe'}});
TestUtils.Simulate.submit(formElement)
The changed value is reflected in the event handlers on First Name. But, not in the test. So, both the fields display missing value validation failing my test.
What I could be doing wrong here?
Below are code:
//NameForm.jsx
'use strict';
var React=require('react')
var forms = require('newforms')
var NameForm = forms.Form.extend({
firstName: forms.CharField({maxLength: 100, label: "First name(s)"}),
lastName: forms.CharField({maxLength: 100, label: "Last name"}),
cleanFirstName(callback) {
callback(null)
},
render() {
return this.boundFields().map(bf => {
return <div className={'form-group ' + bf.status()}>
<label className="form-label" htmlFor={bf.name}>
<span className="form-label-bold">{bf.label}</span>
</label>
{bf.errors().messages().map(message => <span className="error-message">{message}</span>)}
<input className="form-control" id={bf.name} type="text" name={bf.name} onChange = {this.onChangeHandler}/>
</div>
})
}
, onChangeHandler: function(e){
console.log("onchnage on input is called ----- >> " + e.target.value)
}
})
module.exports = {
NameForm
}
Here is NamePage.jsx:
'use strict';
var React = require('react')
var {ErrorObject} = require('newforms')
var superagent = require('superagent-ls')
var {API_URL} = require('../../constants')
var {NameForm} = require('./NameForm')
var NamePage = React.createClass({
contextTypes: {
router: React.PropTypes.func.isRequired
},
propTypes: {
data: React.PropTypes.object,
errors: React.PropTypes.object
},
statics: {
title: 'Name',
willTransitionTo(transition, params, query, cb, req) {
if (req.method != 'POST') { return cb() }
superagent.post(`${API_URL}/form/NameForm`).send(req.body).withCredentials().end((err, res) => {
if (err || res.serverError) {
return cb(err || new Error(`Server error: ${res.body}`))
}
if (res.clientError) {
transition.redirect('name', {}, {}, {
data: req.body,
errors: res.body
})
}
else {
transition.redirect('summary')
}
cb()
})
}
},
getInitialState() {
return {
client: false,
form: new NameForm({
onChange: this.forceUpdate.bind(this),
data: this.props.data,
errors: this._getErrorObject()
})
}
},
componentDidMount() {
this.setState({client: true})
},
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
var errorObject = this._getErrorObject(nextProps.errors)
this.refs.nameForm.getForm().setErrors(errorObject)
}
},
_getErrorObject(errors) {
if (!errors) { errors = this.props.errors }
return errors ? ErrorObject.fromJSON(errors) : null
},
_onSubmit(e) {
e.preventDefault()
var form = this.state.form
form.validate(this.refs.form, (err, isValid) => {
if (isValid) {
this.context.router.transitionTo('name', {}, {}, {
method: 'POST',
body: form.data
})
}
})
},
render() {
return <div>
<h1 className="heading-large">Your name</h1>
<form action='name' method="POST" onSubmit={this._onSubmit} ref="form" autoComplete="off" noValidate={this.state.client}>
{this.state.form.render()}
<button type="submit" className="button">Next</button>
</form>
</div>
},
})
module.exports = NamePage
Here is NameTest.js :
//NameTest.js
var React = require('react')
var ReactAddons = require('react/addons')
var TestUtils = React.addons.TestUtils
var InputFieldItem = require('../../src/page/name/NamePage')
describe('Name page component', function(){
var renderedComponent;
before('render element', function() {
console.log("*** in before")
renderedComponent = TestUtils.renderIntoDocument(
<InputFieldItem />
);
});
it('Only First Name entered should display one error message', function() {
renderedComponent = TestUtils.renderIntoDocument(
<InputFieldItem />
);
var formElement = TestUtils.findRenderedDOMComponentWithTag(renderedComponent, 'form').getDOMNode()
var firstNameElement = TestUtils.scryRenderedDOMComponentsWithTag(renderedComponent, 'input')[0].getDOMNode()
var lastNameElement = TestUtils.scryRenderedDOMComponentsWithTag(renderedComponent, 'input')[1].getDOMNode()
var buttonElement = TestUtils.findRenderedDOMComponentWithTag(renderedComponent, 'button').getDOMNode()
TestUtils.Simulate.change(firstNameElement , {target: {value: 'Joe'}});
TestUtils.Simulate.submit(formElement)
var errorSpans = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'error-message')
console.log("First name value is :|"+ firstNameElement.value + "|")
expect (errorSpans.length).to.equal(1)
})
});

Custom Autocomplete Component Ember Cli not working

I not sure why the return is not being passed to the component template. It's listening and the value is found but its not working.
return result.resources; is not returning the data when result.resoures has an array of objects.
here is the autocomplete template auto-complete.hbs
<ul>
<li class='row input-group-lg'>
{{input type="text" value=searchText placeholder="Enter Street Address" class='col-md-6 col-md-offset-3 col-xs-12 street-address'}}
</li>
</ul>
<ul>
{{#each searchResults}}
<li>{{this.name}}</li>
{{/each}}
</ul>
here is auto-complete.js
import Ember from 'ember';
export default Ember.Component.extend({
searchText: null,
searchResults: function() {
var searchText = this.get('searchText');
if(!searchText) {
return;
}
Ember.$.ajax({
url: "http://dev.virtualearth.net/REST/v1/Locations",
dataType: "jsonp",
data: {
key: "",
q: searchText
},
jsonp: "jsonp"
}).then(function(data) {
var result = data.resourceSets[0];
if (result) {
if (result.estimatedTotal > 0) {
return result.resources;
}
}
});
}.property('searchText')
});
The code block
.then(function(data) {
var result = data.resourceSets[0];
if (result) {
if (result.estimatedTotal > 0) {
return result.resources;
}
}
will return from the promise and will not return the value for the computed property, which obviously means that you are not returning anything for the CP.
A possible work around can be
searchResults: function() {
var searchText = this.get('searchText');
var searchResults = Ember.ArrayProxy.create();
if(!searchText) {
return;
}
Ember.$.ajax({
url: "http://dev.virtualearth.net/REST/v1/Locations",
dataType: "jsonp",
data: {
key: "",
q: searchText
},
jsonp: "jsonp"
}).then(function(data) {
var result = data.resourceSets[0];
if (result) {
if (result.estimatedTotal > 0) {
searchResults.set('content',result.resources);
}
}
});
return searchResults;
}.property('searchText')
You can create an arrayproxy and return the arrayproxy for the CP. Upon completion of the promise, set the result as content to the arrayproxy, which will update the template.

Backbone.js results of fetch doubling

I am trying to use Django and tastypie with backbone.js and mustache. I have set up an example to study those. When using the below code I get results of users doubling as:
-Id User name
-1 yol
-2 dada
-1 yol
-2 dada
--- MY CODE ---
// I think this tastypie adjustment is not related with the problem but i want you to see the //whole code
window.TastypieModel = Backbone.Model.extend({
base_url: function() {
var temp_url = Backbone.Model.prototype.url.call(this);
return (temp_url.charAt(temp_url.length - 1) == '/' ? temp_url : temp_url+'/');
},
url: function() {
return this.base_url();
}
});
window.TastypieCollection = Backbone.Collection.extend({
parse: function(response) {
this.recent_meta = response.meta || {};
return response.objects || response;
}
});
(function($){
// MODELS-COLLECTIOS
//USERS
var User = TastypieModel.extend({
url: USERS_API
});
var Users = TastypieCollection.extend({
model: User,
url:USERS_API
});
//VIEWS
var UsersView = Backbone.View.extend({
render: function(){
// template with ICanHaz.js (ich)
this.el = ich.userRowTpl(this.model.toJSON());
return this;
}
});
//main app
var AppView = Backbone.View.extend({
tagName: 'tbody',
initialize: function() {
this.users = new Users();
this.users.bind('all', this.render, this);
this.users.fetch();
},
render: function () {
// template with ICanHaz.js (ich)
this.users.each(function (user) {
$(this.el).append(new UsersView({model: user}).render().el);
}, this);
return this;
}
});
var app = new AppView();
$('#app').append(app.render().el);
})(jQuery);
I would say you are firing two times the render, because your view is listening to all events, try instead to bind it just to reset and see how it goes:
initialize: function() {
this.users = new Users();
this.users.bind('reset', this.render, this);
this.users.fetch();
},

Dojo Widget Templates

With reference to Simple Login implementation for Dojo MVC / - there is one point i don't understand. With regards to sample from phusick, the login dialog class does a call of dom.byId("dialog-template") - "dialog-template" is an id from the script which is the template for the dialog and should be present in an html template - not in the main html. So if I remove that, the call to dom.byId would fail
so my code structure is as follows
main.html ( calls Only main.js is called - nothing more)
main.js ( Contains the following)
require([
"dojo/_base/declare","dojo/_base/lang","dojo/on","dojo/dom","dojo/Evented",
"dojo/_base/Deferred","dojo/json","dijit/_Widget","dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin","dijit/Dialog",
"widgets/LoginDialog",
"widgets/LoginController",
"dijit/form/Form","dijit/form/ValidationTextBox","dijit/form/Button",
"dojo/domReady!"
], function(
declare,lang,on,dom,Evented,Deferred,JSON,
_Widget,
_TemplatedMixin,
_WidgetsInTemplateMixin,
Dialog,
LoginDialog,
LoginController
) {
// provide username & password in constructor
// since we do not have web service here to authenticate against
var loginController = new LoginController({username: "user", password: "user"});
var loginDialog = new LoginDialog({ controller: loginController});
loginDialog.startup();
loginDialog.show();
loginDialog.on("cancel", function() {
console.log("Login cancelled.");
});
loginDialog.on("error", function() {
console.log("Login error.");
});
loginDialog.on("success", function() {
console.log("Login success.");
console.log(JSON.stringify(this.form.get("value")));
});
});
Now LoginDialog.js and LoginDialogTemplate.html is the templatised widget for the dialog
and LoginController.js is the controller.
My LoginDialog.js is
define([
"dojo/_base/declare","dojo/_base/lang","dojo/on","dojo/dom","dojo/Evented","dojo/_base/Deferred","dojo/json",
"dijit/_Widget","dijit/_TemplatedMixin","dijit/_WidgetsInTemplateMixin",
"dijit/Dialog","dijit/form/Form","dijit/form/ValidationTextBox","dijit/form/Button",
"dojo/text!templates/loginDialogTemplate.html",
"dojo/text!templates/loginFormTemplate.html",
"dojo/domReady!"
], function(
declare,lang,on,dom,Evented,Deferred,JSON,
_Widget,
_TemplatedMixin,
_WidgetsInTemplateMixin,
Dialog,
Form,
Button,
template
) {
return declare([ Dialog, Evented], {
READY: 0,
BUSY: 1,
title: "Login Dialog",
message: "",
busyLabel: "Working...",
// Binding property values to DOM nodes in templates
// see: http://www.enterprisedojo.com/2010/10/02/lessons-in-widgetry-binding-property-values-to-dom-nodes-in-templates/
attributeMap: lang.delegate(dijit._Widget.prototype.attributeMap, {
message: {
node: "messageNode",
type: "innerHTML"
}
}),
constructor: function(/*Object*/ kwArgs) {
lang.mixin(this, kwArgs);
var dialogTemplate = dom.byId("dialog-template").textContent;
var formTemplate = dom.byId("login-form-template").textContent;
var template = lang.replace(dialogTemplate, {
form: formTemplate
});
var contentWidget = new (declare(
[_Widget, _TemplatedMixin, _WidgetsInTemplateMixin],
{
templateString: template
}
));
contentWidget.startup();
var content = this.content = contentWidget;
this.form = content.form;
// shortcuts
this.submitButton = content.submitButton;
this.cancelButton = content.cancelButton;
this.messageNode = content.messageNode;
},
postCreate: function() {
this.inherited(arguments);
this.readyState= this.READY;
this.okLabel = this.submitButton.get("label");
this.connect(this.submitButton, "onClick", "onSubmit");
this.connect(this.cancelButton, "onClick", "onCancel");
this.watch("readyState", lang.hitch(this, "_onReadyStateChange"));
this.form.watch("state", lang.hitch(this, "_onValidStateChange"));
this._onValidStateChange();
},
onSubmit: function() {
this.set("readyState", this.BUSY);
this.set("message", "");
var data = this.form.get("value");
var auth = this.controller.login(data);
Deferred.when(auth, lang.hitch(this, function(loginSuccess) {
if (loginSuccess === true) {
this.onLoginSuccess();
return;
}
this.onLoginError();
}));
},
onLoginSuccess: function() {
this.set("readyState", this.READY);
this.set("message", "Login sucessful.");
this.emit("success");
},
onLoginError: function() {
this.set("readyState", this.READY);
this.set("message", "Please try again.");
this.emit("error");
},
onCancel: function() {
this.emit("cancel");
},
_onValidStateChange: function() {
this.submitButton.set("disabled", !!this.form.get("state").length);
},
_onReadyStateChange: function() {
var isBusy = this.get("readyState") == this.BUSY;
this.submitButton.set("label", isBusy ? this.busyLabel : this.okLabel);
this.submitButton.set("disabled", isBusy);
}
});
});
My loginDialogTemplate.html is as follows
<script type="text/template" id="dialog-template">
<div style="width:300px;">
<div class="dijitDialogPaneContentArea">
<div data-dojo-attach-point="contentNode">
{form}
</div>
</div>
<div class="dijitDialogPaneActionBar">
<div
class="message"
data-dojo-attach-point="messageNode"
></div>
<button
data-dojo-type="dijit.form.Button"
data-dojo-props=""
data-dojo-attach-point="submitButton"
>
OK
</button>
<button
data-dojo-type="dijit.form.Button"
data-dojo-attach-point="cancelButton"
>
Cancel
</button>
</div>
</div>
</script>
Since the template has the id="dialog-template" so I guess when the widget calls the dom.byId("dialog-template"), it throws an error "TypeError: dom.byId(...) is null" at the line :-> var dialogTemplate = dom.byId("dialog-template").textContent;
So what am I doing wrong here?
If i use all the template scripts in the main html it works fine.
Asif,
Since you're passing in the templates in the define function, you don't need the dom.byId() to get the content. Try this:
Remove the elements from your HTML templates.
In LoginDialog.js, change your function arguments to:
...
Button,
dialogTemplate,
formTemplate
You'll need the formTemplate for the next change. I used 'dialogTemplate' instead of your 'template' so it's more obvious how it's replacing the code from the example. Next, change the beginning of the constructor to:
constructor: function(/*Object*/ kwArgs) {
lang.mixin(this, kwArgs);
//var dialogTemplate = dom.byId("dialog-template").textContent;
//var formTemplate = dom.byId("login-form-template").textContent;
var template = lang.replace(dialogTemplate, {
form: formTemplate
});
var contentWidget = new (declare(
...
I only left the commented code in so you can see what I changed. What it does is create a new template string called 'template' by substituting the {form} placeholder in your dialogTemplate HTML with the formTemplate you passed in. Then it's using that new template string to create the widget.