Backbone view in sails .ejs file - javascript

I am trying to access backbone views in sails framework. I fetch data from the server and I am trying to push them to the DOM. Actually, I ve created a model-controller for the tags I store data from mongo to tags model and I return to backbone the url of tags view. I want to display those data to my DOM element. I am trying to find how is it possible to do so in the sails since I am receiving is not defined error. My DOM element code is the following:
51| <div id="profiles" class = 'hashTagsCloud'>
52| <script id="profileTemplate" type="text/template">
>> 53| <%= tagsCloud.tags.join("&nbsp &nbsp &nbsp")%>
54| </script>
55| </div>
tagsCloud is not defined
Where tagsCloud is a item of the json file I got from the server. Backbone code for views:
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function(eventName) {
_.each(this.model.models, function(profile){
var profileTemplate = this.template(profile.toJSON());
//push data to obj for map script
obj = profile.toJSON();
// Add data to DOM element
$(this.el).html(profileTemplate);
}, this);
return this;
}
});
The above backbone logic works like a charm in apache. However in sails I got not defined error. How can I define, in proper way, a view for tagsCloud item in my index file??
My json file is the following:
[
{
tstamp: 1366626103000,
tagsCloud: {
sort: "asc",
tags: [
"Lorem ipsum dolor sit amet consectetur"
]
},
id: "529da369380eb213e804a673"
}
]
Moreover I add some actions in my homeController file so as to send to ejs file the json data:
index: function (req,res)
{
console.log(req.tags); // tags is the name of the model-controller
res.view({
tags: req.tags
});
},
'home': function (req,res)
{
res.view();
}
Is there anything I ve to change in backbone view code to properly update my index view???

Finally I found a way to send fetched data to the DOM from the backbone. I ve changed template code inside backbone code, so as to send directly the data to the DOM element. Here is my code:
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};
var TagsView = Backbone.View.extend({
el: "#profiles",
template: _.template("<div><p>{{ tg.tagsCloud.tags }}</p></div>"),
render: function(eventName) {
_.each(this.model.models, function(tags){
var tagsTemplate = this.template(tags.toJSON());
//push data to obj for map script
tg = tags.toJSON();
// Add data to DOM element
$(this.el).html(tagsTemplate);
}, this);
return this;
}
});

Related

Using tagName and className properties on Backbone View Vs using template

I have a Backbone View that is using a Backbone Collection to pull data from an api:
var HousesView = Backbone.View.extend({
initialize: function() {
this.collection = new Houses();
var that = this;
this.collection.fetch({
data: {
pageSize: 50
},
success: function () {
that.render();
},
error: function () {
console.error('There was an error in fetch');
}
});
},
tagName: 'section',
template: Handlebars.getTemplate('houses'),
render: function() {
this.$el.html(this.template({ houses : this.collection.toJSON() }));
return this;
}
});
It then creates models from the json pulled from the api and passes that as a collection to my template which takes each model and for e.g.just outputs the name attribute of that model as a list. That works fine.
My question is: because I am using a template to parse the data from this.collection.toJSON() the tagName I set on HouseView doesn't seem to be output in the html. If I am using a template for a View does this mean properties like tagName, className etc wont be output?
Also, ideally I would like to create a HouseView for each model from the collection and then display all of those in a wrapper HousesView.
In your example you are using custom rendered. In that case the auto generation of view from tagName, className and id will be spiked (overwrites by method this.$el.html in render function.).
The best approach is as you mentioned to create separate view and append it in render of main view to html.

general backbone/marionette program structure

I need some general guidelines on how to structure a backbone/marionette application. Im very new to these frameworks and also to js in general.
Basically I have two pages and each page has a list. I have set up an application and a router for the application:
var app = new Backbone.Marionette.Application();
app.module('Router', function(module, App, Backbone, Marionette, $, _){
module.AppLayoutView = Marionette.Layout.extend({
tagName: 'div',
id: 'AppLayoutView',
template: 'layout.html',
regions: {
'contentRegion' : '.main'
},
initialize: function() {
this.initRouter();
},
...
});
module.addInitializer(function() {
var layout = new module.AppLayoutView();
app.appRegion.show(layout);
});
});
In the initRouter I have two functions, one for each page that gets called by router depending on the url.
The function for the content management page looks like this:
onCMNavigated: function(id) {
var cMModule = App.module("com");
var cM = new cMModule.ContentManagement({id: id, region: this.contentRegion});
contentManagement.show();
this.$el.find('.nav-item.active').removeClass('active');
this.cM.addClass('active');
}
So if this is called, I create a new instance of ContentManagement model. In this model, when show() is called, I fetch the data from a rest api, and I parse out an array of banners that need to be shown in a list view. Is that ok? The model looks like the following:
cm.ContentManagement = Backbone.Model.extend({
initialize: function (options) {
this.id = options.id;
this.region = options.region;
},
show: function() {
var dSPage = new DSPage({id: this.id});
dSPage.bind('change', function (model, response) {
var view = new cm.ContentManagementLayoutView();
this.region.show(view);
}, this);
dSPage.fetch({
success: function(model, response) {
// Parse list of banners and for each create a banner model
}
}
});
cm.ContentManagementLayoutView = Marionette.Layout.extend({
tagName: 'div',
id: 'CMLayoutView',
className: 'contentLayout',
template: 'contentmanagement.html',
regions: {
'contentRegion' : '#banner-list'
}
});
Now my biggest doubt is how do I go on from here to show the banner list? I have created a collectionview and item view for the banner list, but is this program structure correct?
do You really need marionnete to manage your application ? especially You are beginner as me too :)
try pure backbone first. You can still use marionette as a library.
backbone MVC architecture is described perfectly on many sites.

Meteor Iron Router : Passing data between routes

How do I pass data between two different routes and templates?
I have a javascript file on the front end (client folder) that simply calls Router.go() passing in the post ID as one of my parameters.
Below are the three main culprits (I believe). I've removed most of the code to make it easier to read. I can change to the PostDetail page with no problems. I can also retrieve the PostId on the PostDetail page from the Router. My problem is, the database entry (POLL) that is retrieved does not get rendered on the template. Hence {{Question}} is always blank even though the database entry is being returned.
Let me know if I should post more information.
FrontEnd.js
Template.PostTiles.events({
// When a choice is selected
'click .pin' : function(event, template) {
Router.go('Post', {_PostId: this.PostId});
}
});
post-detail.html
<template name="PostDetail">
<h3>{{Question}}</p>
</template>
Shared.js
Router.map( function() {
this.route('Home', {
path: '/',
template: 'PostTiles',
data: {
// Here we can return DB data instead of attaching
// a helper method to the Template object
QuestionsList: function() {
return POLL.find().fetch();
}
}
});
this.route('Post', {
template: 'PostDetail',
path: '/Post/:_PostId',
data: function() {
return POLL.findOne(this.params._PostId);
},
renderTemplates: {
'disqus': {to: 'comments'}
}
});
});
----- Update -----
I think I've narrowed down the issue to simply being able to render only one Database entry, instead of a list of them using the {{#each SomeList}} syntax.
Looks like you found the answer / resolved this, but just in case, I think it's in your findOne statement:
data: function() {
return POLL.findOne(this.params._PostId);
},
should read:
data: function() {
return POLL.findOne({_id:this.params._PostId});
},
(assuming that POLL has your posts listed by _id.
Hope that helps.
Could you pass the info in the Session? the docs for that are here http://docs.meteor.com/#session. That's what I'm planning on doing.

Individual view from an item in an ArrayController

I have an ember.js model and controller setup like so:
//model
App.Order = Ember.Object.extend({
content: null,
create: function(data) {
this.set('content', data);
return this._super();
}
});
//orders controller
App.ordersController = Ember.ArrayController.create({
content: [],
init: function() {
var self = this;
var orders = [];
$.getJSON('js/data.json', function(data) {
data.forEach(function(item) {
var order = App.Order.create(item);
orders.push(order);
});
self.set('content', orders);
});
},
selectItem: function(data) {
alert(data);
}
});
With the following view:
{{#each App.ordersController}}
<div {{action selectItem target="App.ordersController"}}>{{order_number}}</div>
{{/each}}
Which prints out a list of orders with a click action that alerts the corresponding item. This works fine.
What I want to do is show a clicked item in a separate view, eventually with the goal of creating a floating dialogue with orders details shown. I'm new to ember and not sure how this should be implemented. I have a function selectItem which alert's a clicked order but I need to link this to a separate view and print the order details.
Should I store the selected item in a separate controller with a corresponding view and update this when selectItem is clicked? Or could I update a sperate view from the ordersController? Any advice is much appreciated.
When you use the router ember does the instantiation of your class for you. By specifing the "orders" route is looks for a template called orders and a controller called OrdersController if it can't find one it'll generate one for you. (I've omitted the controller for clearity). To load your model from a json source you could have a look at ember-data.
here is a jsfiddle so you can fiddle with it a bit.
You should definitely have a look here these are guides for ember that really help you on the way. The documentation is getting better and better. :)
JS:
window.App = App = Em.Application.create();
//model
App.Order = Ember.Object.extend({
order_number: null,
});
//we create 2 routes one for all the order and one per specific order
App.Router.map(function(){
this.resource('orders', { path: "/" });
this.resource("order", { path: "/:order_id" });
});
//the route supplies the model and handles the event to transition to a new route.
App.OrdersRoute = Em.Route.extend({
events: {
selectItem: function (orderId) {
//select the order by the "orderId" you want as a model for your new view.
this.transitionTo("order", order);
}
},
model: function(){
return content; //an array containing the orders;
}
});
//supplies the model for the "order" route by selecting one acording to the params;
App.OrderRoute = Em.Route.extend({
model: function(params){
return order; //select an object from the array according to the params
},
});
HBS:
<script type="text/x-handlebars" data-template-name="orders">
{{#each controller}}
<!-- this calls the event handler "selectItem" on the ordersroute -->
<div {{action "selectItem" order_number}}>{{order_number}}</div>
{{/each}}
<!-- this is handled by "App.OrderRoute" -->
<a href="#/3"/>with a direct link</a>
</script>
<script type="text/x-handlebars" data-template-name="order">
{{content.order_number}}
{{#linkTo "orders"}}Back to orders{{/linkTo}}
</script>

Backbone.js - how to handle "login"?

Hi I'm trying to wrap my head around backbone.js for some days now but since this is my first MVC Framework, it's pretty hard.
I can easily get my Collections to work, fetching data from the server etc, but it all depends on first "logging" in per API-Key. I just don't know how to model this with a good MVC approach. (btw: I can't use the Router/Controller because it's a Chrome Extension)
The Flow looks like this:
Start Extension
Is there an API-Key in localStorage?
No => Display a input field and a save button which saves the key to localStorage; Yes => proceed with the Application:
App......
The only way I could think of it is putting it all together in a big View... but I guess since I am fairly new to this there are surely some better approaches.
You can create a model that maintains the state of the user's login status and a view that renders a different template depending on that status. The view can show the "input field" template if the user is not logged in and a different template if the user is. I would keep all access to localStorage in the Model because the View should not be concerned with persistence. The view should probably not be concerned with the API Key as well, and that's why I have my view binding to the model's loggedIn change ('change:loggedIn') instead of apiKey change...although I am showing the API key in one of my templates for demonstration purpose only. Here's my very simplified sample. Note that I didn't bother with validating the API Key, but you'll probably want to:
Templates:
<script id="logged_in" type="text/html">
You're logged in. Your API key is <%= escape('apiKey') %>. Let's proceed with the application...
</script>
<script id="not_logged_in" type="text/html">
<form class="api_key">
API Key: <input name="api_key" type="text" value="" />
<button type="sumit">Submit</button>
</form>
</script>
Backbone Model and View:
var LoginStatus = Backbone.Model.extend({
defaults: {
loggedIn: false,
apiKey: null
},
initialize: function () {
this.bind('change:apiKey', this.onApiKeyChange, this);
this.set({'apiKey': localStorage.getItem('apiKey')});
},
onApiKeyChange: function (status, apiKey) {
this.set({'loggedIn': !!apiKey});
},
setApiKey: function(apiKey) {
localStorage.setItem('apiKey', apiKey)
this.set({'apiKey': apiKey});
}
});
var AppView = Backbone.View.extend({
_loggedInTemplate: _.template($('#logged_in').html()),
_notLoggedInTemplate: _.template($('#not_logged_in').html()),
initialize: function () {
this.model.bind('change:loggedIn', this.render, this);
},
events: {
'submit .api_key': 'onApiKeySubmit'
},
onApiKeySubmit: function(e){
e.preventDefault();
this.model.setApiKey(this.$('input[name=api_key]').val());
},
render: function () {
if (this.model.get('loggedIn')) {
$(this.el).empty().html(this._loggedInTemplate(this.model));
} else {
$(this.el).empty().html(this._notLoggedInTemplate(this.model));
}
return this;
}
});
var view = new AppView({model: new LoginStatus()});
$('body').append(view.render().el);

Categories

Resources