How to access model from within a view in emberjs using javascript? - javascript

How do I access the model defined in index route model hook from within the container init function I want the container to iterate on the model and create child view for each object in the model array?
Here is the code sample:
App= Ember.Application.create();
App.Router.map(function(){
})
App.IndexRoute=Ember.Route.extend({
model: function(){
return arr;
}
})
App.MainView = Em.View.extend({
classNames: ['mainView']
});
App.MyContainerView = Em.ContainerView.extend({
tagName:"tbody",
});
var container = App.MyContainerView.create({
init: function() {
//this._super();
//this.pushObject(App.FirstView.create());
//this.pushObject(App.SecondView.create());
}
});
App.SingleTaskView = Em.View.extend({
templateName:'single-task',
tagName:""
});
App.IndexController= Ember.ArrayController.extend({
actions: {
newTask: function(){
var containerView = Em.View.views['my_container_view']
var childView = containerView.createChildView(App.SingleTaskView);
containerView.get('childViews').pushObject(childView);
}
}
});

You are using deprecated items (ArrayController, ContainerView) cf release note
Which version of Ember are you using ?

Related

How do i pass a received array into underscore template

I am getting a long array from PHP containing various data objects.
[{"commid":"1","uid":"0","pid":"3","comment":"comm","parid":null,"date":"2016-10-27 15:03:10"},
{"commid":"2","uid":"0","pid":"10","comment":"Ana","parid":null,"date":"2016-10-27 15:03:51"},
{"commid":"3","uid":"0","pid":"5","comment":"asss!","parid":null,"date":"2016-10-27 15:05:50"},
{"commid":"4","uid":"0","pid":"10","comment":"Lawl?","parid":null,"date":"2016-10-27 17:03:59"},
{"commid":"5","uid":"0","pid":"14","comment":"sd","parid":null,"date":"2016-11-06 00:25:04"},
{"commid":"6","uid":"0","pid":"14","comment":"sds","parid":null,"date":"2016-11-06 00:25:50"},
{"commid":"7","uid":"0","pid":"14","comment":"WOW!","parid":null,"date":"2016-11-08 15:06:18"},
{"commid":"8","uid":"0","pid":"13","comment":"Hello!?","parid":null,"date":"2016-11-08 15:14:30"}]
My Backbone View which will be rendering the data is
var WorkPage = Backbone.View.extend({
el: $('#indexcontent'),
render: function() {
Backbone.history.navigate('work');
var _this = this;
this.$el.html(workHTML);
$.ajax({
type: "GET",
url: "includes/server_api.php/work",
data: '',
cache: false,
success: function(html) {
console.log(html);
var compiledTemplate = _.template($('#content-box').html(), html);
_this.$el.html(compiledTemplate);
},
error: function(e) {
console.log(e);
}
});
return false;
}
});
My workHTML which will be rendered by Underscore is
<script type="text/template" id="content-box">
<div class="workhead">
<h3 class="msg comment"><%= comment%></h3>
<p class="date"><%= date%></p>
</div>
</script>
<div id="content-box-output"></div>
How do I implement a underscore loop here?
You should take advantage of Backbone's features. And to do that, you need to understand how to use a REST API with Backbone.
Backbone's Model is made to manage a single object and handle the communication with the API (GET, POST, PATCH, PUT requests).
Backbone's Collection role is to handle an array of model, it handles fetching it (GET request that should return a JSON array of objects) and it also parse each object into a Backbone Model by default.
Instead of hard-coding a jQuery ajax call, use a Backbone collection.
var WorkCollection = Backbone.Collection.extend({
url: "includes/server_api.php/work",
});
Then, modularize your views. Make an item view for each object of the array you received.
var WorkItem = Backbone.View.extend({
// only compile the template once
template: _.template($('#content-box').html()),
render: function() {
// this is how you pass data to the template
this.$el.html(this.template(this.model.toJSON()));
return this; // always return this in the render function
}
});
Then your list view looks like this:
var WorkPage = Backbone.View.extend({
initialize: function(options) {
this.itemViews = [];
this.collection = new WorkCollection();
this.listenTo(this.collection, 'reset', this.render);
// this will make a GET request to
// includes/server_api.php/work
// expecting a JSON encoded array of objects
this.collection.fetch({ reset: true });
},
render: function() {
this.$el.empty();
this.removeItems();
this.collection.each(this.renderItem, this);
return this;
},
renderItem: function(model) {
var view = new WorkItem({
model: model
});
this.itemViews.push(view);
this.$el.append(view.render().el);
},
// cleanup to avoid memory leaks
removeItems: function() {
_.invoke(this.itemViews, 'remove');
this.itemViews = [];
}
});
It's unusual to set the url in the render function, you should keep the responsibilities scoped to the right place.
The router could be something like:
var Router = Backbone.Router.extend({
routes: {
'work': 'workPage'
},
workPage: function() {
var page = new WorkPage({
el: $('#indexcontent'),
});
}
});
Then, if you want to see the work page:
var myRouter = new Router();
Backbone.history.start();
myRouter.navigate('#work', { trigger: true });
Templates and RequireJS
My index.html page contains this
indexcontent div but the content-box which contains the template
format which we are compiling is stored in different work.html. So,
if i dont load this work.html in my main index.html i am unable to
access content-box.
I would recommend to use the text require.js plugin and load each template for the view like this:
The work-item.js file:
define([
'underscore', 'backbone',
'text!templates/work-item.html',
], function(_, Backbone, WorkItemTemplate) {
var WorkItem = Backbone.View.extend({
template: _.template(WorkItemTemplate),
/* ...snip... */
});
return WorkItem;
});
The work-page.js file:
define([
'underscore', 'backbone',
'text!templates/work-page.html',
], function(_, Backbone, WorkPageTemplate) {
var WorkPage = Backbone.View.extend({
template: _.template(WorkPageTemplate),
});
return WorkPage;
});
In your index.html file you need to have _.each() method to iterate throught each element
<% _.each(obj, function(elem){ %>
<div class="workhead">
<h3 class="msg comment"><%= elem.comment %></h3>
<p class="date"><%= elem.date%></p>
</div>
<% }) %>
I make variable of your response just to have data to work with. In your View you need to set point on template
template: _.template($("#content-box").html()), and in render method just send data as object.
Here is working code : jsFiddle
Here is one way to load the template for each value in the data array.
var WorkPage = Backbone.View.extend({
el: $('#indexcontent'),
render: function() {
Backbone.history.navigate('work');
var _this = this;
this.$el.html(workHTML);
$.ajax({
type: "GET",
url: "includes/server_api.php/work",
data: '',
cache: false,
success: function(data) {
console.log(data);
var $div = $('<div></div>');
_.each(data, function(val) {
$div.append(_.template($('#content-box').html(), val));
});
_this.$el.html($div.html());
},
error: function(e) {
console.log(e);
}
});
return false;
}
});

Model method error while trying to navigate

I have several Backbone Models rendered in a Collection View, and also I have a route that should render a view of that model. So, here come the views
resume.js
// this renders a single model for a collection view
var ResumeView = Backbone.View.extend({
model: new Resume(),
initialize: function () {
this.template = _.template($('#resume').html());
},
render: function () {
this.$el.html(this.template(this.model.toJSON));
return this;
}
});
#resume template
<section id="resume">
<h1><%= profession %></h1>
<!-- !!!!! The link for a router which should navigate to ShowResume view -->
View Details
</section>
Collection view:
var ResumeList = Backbone.View.extend({
initialize: function (options) {
this.collection = options.collection;
this.collection.on('add', this.render, this);
// Getting the data from JSON-server
this.collection.fetch({
success: function (res) {
_.each(res.toJSON(), function (item) {
console.log("GET a model with " + item.id);
});
},
error: function () {
console.log("Failed to GET");
}
});
},
render: function () {
var self = this;
this.$el.html('');
_.each(this.collection.toArray(), function (cv) {
self.$el.append((new ResumeView({model: cv})).render().$el);
});
return this;
}
});
The code above works perfectly and does exactly what I need -- an array of models is fetched from my local JSON-server and each model is displayed within a collection view. However, the trouble starts when I try to navigate through my link in the template above. Here comes the router:
var AppRouter = Backbone.Router.extend({
routes: {
'': home,
'resumes/:id': 'showResume'
},
initialize: function (options) {
// layout is set in main.js
this.layout = options.layout
},
home: function () {
this.layout.render(new ResumeList({collection: resumes}));
},
showResume: function (cv) {
this.layout.render(new ShowResume({model: cv}));
}
});
and finally the ShowResume view:
var ShowResume = Backbone.View.extend({
initialize: function (options) {
this.model = options.model;
this.template = _.template($('#full-resume').html());
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
}
});
I didn't provide the template for this view because it is quite large, but the error is following: whenever I try to navigate to a link, a view tries to render, but returns me the following error: Uncaught TypeError: this.model.toJSON is not a function. I suspect that my showResume method in router is invalid, but I can't actually get how to make it work in right way.
You are passing the string id of the url 'resumes/:id' as the model of the view.
This should solve it.
showResume: function (id) {
this.layout.render(new ShowResume({
model: new Backbone.Model({
id: id,
profession: "teacher" // you can pass data like this
})
}));
}
But you should fetch the data in the controller and react accordingly in the view.
var AppRouter = Backbone.Router.extend({
routes: {
'*otherwise': 'home', // notice the catch all
'resumes/:id': 'showResume'
},
initialize: function(options) {
// layout is set in main.js
this.layout = options.layout
},
home: function() {
this.layout.render(new ResumeList({ collection: resumes }));
},
showResume: function(id) {
// lazily create the view and keep it
if (!this.showResume) {
this.showResume = new ShowResume({ model: new Backbone.Model() });
}
// use the view's model and fetch
this.showResume.model.set('id', id).fetch({
context: this,
success: function(){
this.layout.render(this.showResume);
}
})
}
});
Also, this.model = options.model; is unnecessary as Backbone automatically picks up model, collection, el, id, className, tagName, attributes and events, extending the view with them.

How to separate code: is my controller doing too much work?

Here is a description of the code below:
router decides which controller method to call
controller gets model(s)
controller instantiates various views with model
controller instantiates layout, puts views into it
controller puts layout into app
Is controller doing too many things? I guess the good way should be
router decides which controller method to call
controller gets model(s)
controller instantiates layout with model
controller puts layout into app. End of controller's work
layout when initialized instantiates views with model
Question: Is the second approach better?
If so, how to do [3. and 5. of the good way]?
Code also in jsfiddle
ContactMgr.Router = Marionette.AppRouter.extend({
appRoutes: {
'contacts/:id' : 'detail'
}
});
ContactMgr.Controller = Marionette.Controller.extend({
detail: function (id) {
var promise = App.request('contact:entities', id);
$.when(promise).done( function (contacts) {
var _model = contacts.get(id);
var contactView = new MyContactView({ model: _model });
var sideView = new MySideView({ model: _model });
var view = new MyLayout();
// MyLayout has mainRegion, sideRegion
view.on('show', function (v) {
v.getRegion('mainRegion').show(contactView);
v.getRegion('sideRegion').show(sideView);
});
App.getRegion('contentRegion').show(view);
// App has contentRegion, other regions
});// when done, end
}// detail, end
});
This may be the answer.
And
ContactMgr.Controller = Marionette.Controller.extend({
detail: function (id) {
...
var _model = contacts.get(id);
...
var view = new MyLayout({model: _model});
App.getRegion('contentRegion').show(view);
}
});
MyLayout = Marionette.Layout.extend({
...
regions: {
mainRegion: '#...',
sideRegion: '#...'
},
contactView: null,
sideView: null,
onShow: function () {
this.getRegion('mainRegion').show(this.contactView);
this.getRegion('sideRegion').show(this.sideView);
},
initialize: function (opt) {
var _model = opt.model;
this.contactView = new Marionette.ItemView({ model: _model });
this.sideView = new Marionette.ItemView({ model: _model });
}
});

Using views in backbone.js

I'm currently learning backbone.js and have a little problem. I dont' quite get how the view works.
I have created a model, a collection, and another model that again contains the collection:
Sensor = Backbone.Model.extend({
defaults: {
channel: '',
name: '',
temperature: 0,
tempMin: 0,
tempMax: 0
}
});
SensorList = Backbone.Collection.extend({
model: Sensor
});
Now I created a view, so I am able to render the sensor collection with handlebar.js template:
TemperatureView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function(eventName) {
var source = $('#sensor-list-template').html();
var template = Handlebars.compile(source);
var html = template(this.collection.toJSON());
this.$el.html(html);
} 
});
Now I want to load some data and render the information. But I don't know how to get the data into my view...I tried this:
$(document).ready(function() {
var temps = new TemperatureRequest();
temps.fetch({
success: function() {
console.log(temps);
var test = temps.get("sensors");
console.log(test);
var tempView = new TemperatureView({
collection: test
});
}
});
});
The data is fetched correctly. I have a collection of sensors. And now I want to pass them to the view so it is getting rendered....but I don't understand how this is done..pls help!
Since you are passing the collection to the view while creating it, you can access the same using this.collection inside your view anywhere.
var tempView = new TemperatureView({
collection: test
});
More over you have added the render function inside your initialize , it automatically calls the render function.Inside the render it fetches the collection and since your template needs only json object you are converting your collection it to json array objects.Templates takes care of appending the values to html.
If you want to add automatic view render to happen whenever the collection removes a model or adds a model into it you can add a listener and callback function to it
initialize : function(){
console.log("initializing view");
this.collection.on('add', this.render, this);
this.collection.on('reset', this.render, this);
this.render();
}
I just got it. Took me a while and I have definitly some reading to do.
There were several problems. First of all I have to overwrite the parse function, so the collection is stored correctly in my model:
TemperatureRequest = Backbone.Model.extend({
urlRoot: '/temperatures',
defaults: {
timestamp: '',
logfile: '',
sensorList: new SensorList()
},
parse: function(response) {
response.sensorList = new SensorList(response.sensors);
return response;
},
success: function(response) {
console.log('success');
}
});
In my view I know add the listen to events as suggested and also fetch the data within the initialize function to get rid of the success callback:
TemperatureView = Backbone.View.extend({
el: '#temperatures',
initialize: function() {
this.listenTo(this.model, 'reset', this.render);
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'add', this.render);
this.model.fetch();
},
render: function(eventName) {
var list = this.model.get('sensorList');
console.log(list.toJSON());
var source = $('#sensor-list-template').html();
var template = Handlebars.compile(source);
var html = template(list.toJSON());
this.$el.html(html);
this.renderTimestamp();
},
renderTimestamp: function() {
var tsText = $("<p></p>").addClass("text-right");
var timestamp = $("<div></div>").addClass("col-sm-4 col-sm-offset-8").append(tsText);
tsText.text(this.model.get('timestamp'));
$('#timestamp').append(timestamp);
}
});
now I can do this to render the data:
$(document).ready(function() {
var temps = new TemperatureRequest();
var tempsView = new TemperatureView({
model: temps
});
});
Instead of passing the collection to the view I pass the model to it and fetch the data inside of the initialize function.
What I still don't understand is when I have to use "this" and when I have to use _bindAll...

Uncaught TypeError: Object function (){return i.apply(this,arguments)} has no method 'on'

For some reasons, I keep on getting this error, (See attached screenshot). I've tried adding a _.bindAll(this); and even tried upgrading my code to have the latest version of backbonejs. Still no luck.
Can someone help me on this?
var app = app || {};
(function ($) {
'use strict';
app.EmployeeView = Backbone.View.extend({
el: '#container',
model: app.Employee,
events: {
'click #save' : 'saveEntry'
},
initialize: function(){
console.log('Inside Initialization!');
this.$empName = this.$('#txtEmpName');
this.$department = this.$('#txtDepartment');
this.$designation = this.$('#txtDesignation');
this.listenTo(app.employees, 'add', this.addEmployee);
app.employees.fetch();
console.log('End of Initialization!');
//this.render();
},
render: function () {
console.log('Inside Render!!');
console.log(this.model);
this.$el.html(this.template(this.model.toJSON()));
console.log('Inside End of Render!!');
return this;
},
newAttributes: function(){
return{
empName: this.$empName.val(),
department: this.$department.val(),
designation: this.$designation.val()
};
},
saveEntry: function(){
console.log('Inside SaveEntry!');
//console.log(this.newAttributes());
console.log('this.model');
console.log(app.Employee);
//app.employees.create(this.newAttributes());
app.Employee.set(this.newAttributes());
app.employees.add(app.Employee);
console.log('After SaveEntry!');
},
addEmployee: function (todo) {
var view = new app.EmployeeItemView({ model: app.Employee });
$('#empInfo').append(view.render().el);
}
})
})(jQuery);
Code for "collections/employees.js"
var app = app || {};
(function (){
console.log('Inside collection');
var Employees = Backbone.Collection.extend({
model: app.Employee,
localStorage: new Backbone.LocalStorage('employee-db')
});
app.employees = new Employees();
})();
Code for "model/employee.js"
var app = app || {};
(function(){
'use strict';
app.Employee = Backbone.Model.extend({
defaults: {
empName: '',
department: '',
designation: ''
}
});
})();
You're saying this in your view:
model: app.Employee
app.Employee looks like a model "class" rather than a model instance. Your view wants a model instance in its model property. Normally you'd say something like this:
var employee = new app.Employee(...);
var view = new app.EmployeeView({ model: employee });
this.model.toJSON() won't work since this.model is the app.Employee constructor. Actually I don't see any meaning in your EmployeeView.render method. If it is aggregate view why you have model on it? Otherwise what is the second view class EmployeeItemView? If you're following ToDo MVC example you can see that there is no model in AppView, that is why I conclude you need not model in your EmployeeView. And render method you provided seems to belong to EmployeeItemView.
Secondly, you call app.Employee.set which is also a call on a constructor not on an object. I think you meant
saveEntry: function(){
console.log('Inside SaveEntry!');
app.employees.create(this.newAttributes());
console.log('After SaveEntry!');
},
If you want to pass a model to app.EmployeeItemView you should use callback argument.
addEmployee: function (employee) {
var view = new app.EmployeeItemView({ model: employee });
$('#empInfo').append(view.render().el);
}

Categories